canvas实现飞机打怪兽射击小游戏的示例代码

2019-01-28 21:08:37丽君

定义飞机

飞机对象包含特有属性:状态、宽高、图像、横坐标最大最小值,有 hasHit()、draw()、direction()、shoot()、drawBullets() 方法。

/*飞机*/ var Plane = function (opts) { this.opts = opts || {}; Element.call(this, opts); //特有属性状态和图像 this.status = 'normal'; this.width = opts.width; this.height = opts.height; this.planeIcon = opts.planeIcon; this.minX = opts.minX; this.maxX = opts.maxX; //子弹相关 this.bullets = []; this.bulletSpeed = opts.bulletSpeed || CONFIG.bulletSpeed; this.bulletSize = opts.bulletSize || CONFIG.bulletSize; }; //继承Element方法 inheritPrototype(Plane, Element); //方法:子弹击中目标 Plane.prototype.hasHit = function (enemy) { var bullets = this.bullets; for (var i = bullets.length - 1; i >= 0; i--) { var bullet = bullets[i]; var isHitPosX = (enemy.x < bullet.x) && (bullet.x < (enemy.x + enemy.size)); var isHitPosY = (enemy.y < bullet.y) && (bullet.y < (enemy.y + enemy.size)); if (isHitPosX && isHitPosY) { this.bullets.splice(i, 1); return true; } } return false; }; //方法:绘制飞机 Plane.prototype.draw = function () { this.drawBullets(); var planeIcon = new Image(); planeIcon.src = this.planeIcon; ctx.drawImage(planeIcon, this.x, this.y, this.width, this.height); return this; }; //方法:飞机方向 Plane.prototype.direction = function (direction) { var speed = this.speed; var planeSpeed; if (direction === 'left') { planeSpeed = this.x < this.minX ? 0 : -speed; } else { planeSpeed = this.x > this.maxX ? 0 : speed; } console.log('planeSpeed:', planeSpeed); console.log('this.x:', this.x); console.log('this.minX:', this.minX); console.log('this.maxX:', this.maxX); this.move(planeSpeed, 0); return this;//方便链式调用 }; //方法:发射子弹 Plane.prototype.shoot = function () { var bulletPosX = this.x + this.width / 2; this.bullets.push(new Bullet({ x: bulletPosX, y: this.y, size: this.bulletSize, speed: this.bulletSpeed })); return this; }; //方法:绘制子弹 Plane.prototype.drawBullets = function () { var bullets = this.bullets; var i = bullets.length; while (i--) { var bullet = bullets[i]; bullet.fly(); if (bullet.y <= 0) { bullets.splice(i, 1); } bullet.draw(); } };
hasHit() 判断飞机发射的子弹是否击中怪兽,主要是判断子弹的横坐标是否在[怪兽横坐标,怪兽横坐标+怪兽高度]范围内,同时子弹的纵坐标在[怪兽纵坐标,怪兽纵坐标+怪兽宽度]范围内,击中返回 true,并移除该子弹。 draw() 绘制子弹和飞机。 direction() 因为飞机移动范围有左右边界,需要判断飞机横坐标是否到达边界,如果到达边界 planeSpeed 为 0,不再移动。 shoot() 创建子弹对象,保存到 bullets 数组,子弹横坐标为飞机横坐标加上飞机宽度的一半。 drawBullets() 绘制子弹,从数组最后往回遍历子弹对象数组,调用子弹 fly() 方法,如果子弹向上飞出屏幕,则移除这颗子弹。