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

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

move(x, y) 方法根据传入的 (x, y) 值自叠加。

定义怪兽

怪兽包含特有属性:怪兽状态、图像、控制爆炸状态持续的 boomCount ,和 draw()、down()、direction()、booming() 方法。

/*敌人*/ var Enemy = function (opts) { this.opts = opts || {}; //调用父类属性 Element.call(this, opts); //特有属性状态和图像 this.status = 'normal';//normal、booming、noomed this.enemyIcon = opts.enemyIcon; this.enemyBoomIcon = opts.enemyBoomIcon; this.boomCount = 0; }; //继承Element方法 inheritPrototype(Enemy, Element); //方法:绘制敌人 Enemy.prototype.draw = function () { if (this.enemyIcon && this.enemyBoomIcon) { switch (this.status) { case 'normal': var enemyIcon = new Image(); enemyIcon.src = this.enemyIcon; ctx.drawImage(enemyIcon, this.x, this.y, this.size, this.size); break; case 'booming': var enemyBoomIcon = new Image(); enemyBoomIcon.src = this.enemyBoomIcon; ctx.drawImage(enemyBoomIcon, this.x, this.y, this.size, this.size); break; case 'boomed': ctx.clearRect(this.x, this.y, this.size, this.size); break; default: break; } } return this; }; //方法:down 向下移动 Enemy.prototype.down = function () { this.move(0, this.size); return this; }; //方法:左右移动 Enemy.prototype.direction = function (direction) { if (direction === 'right') { this.move(this.speed, 0); } else { this.move(-this.speed, 0); } return this; }; //方法:敌人爆炸 Enemy.prototype.booming = function () { this.status = 'booming'; this.boomCount += 1; if (this.boomCount > 4) { this.status = 'boomed'; } return this; }
draw() 主要是根据怪兽的状态绘制不同的图像。 down() 调用父类 move() 方法,传入 y 值控制怪兽向下移动。 direction() 根据传入的方向值控制左/右移动。 booming() 让爆炸状态持续4帧,4帧后再消失。

定义子弹

子弹有 fly() 、draw() 方法。

/*子弹*/ var Bullet = function (opts) { this.opts = opts || {}; Element.call(this, opts); }; inheritPrototype(Bullet, Element); //方法:让子弹飞 Bullet.prototype.fly = function () { this.move(0, -this.speed); return this; }; //方法:绘制子弹 Bullet.prototype.draw = function () { ctx.beginPath(); ctx.strokeStyle = '#fff'; ctx.moveTo(this.x, this.y); ctx.lineTo(this.x, this.y - CONFIG.bulletSize); ctx.closePath(); ctx.stroke(); return this; };
fly() 调用父类 move() 方法,传入 y 值控制子弹向上移动。 draw() 因为子弹其实就是一条长度为 10 的直线,通过绘制路径的方式画出子弹。