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; } |
定义子弹
子弹有 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; }; |









