前回作ったPlayerとPlayerBullet1は共通する処理があったので、今回は継承(?)を使って共通する処理をまとめてみた。ついでにEnemy1も作成した。ただ、まだ敵はでてこない。まずは共通する処理をまとめたGameObject.js
var GameObject = function(){ this.move = function(x, y){ this.position.move(x, y) } this.dmove = function(dx, dy){ this.position.dmove(dx, dy); } this.applyDamage = function(damage){ this.life -= damage; this.life = this.life < 0 ? 0 : this.life; return this.life > 0; } this.intersect = function(object){ return this.getRect().intersect(object.getRect()); } }
次にPlayer.js。使う必要がなさそうなのでthis.imageを削除してimageをそのまま使うようにした。あとはGameObjectを継承するようにしている
var Player = function(image){ this.position = new Point(); this.rect = new Rect(); this.life = 300; this.damage = 300; this.score = 10000; this.fire = false; var direction = 0; var fireCount = 0; this.draw = function(context){ context.drawImage(image, this.position.x, this.position.y); } this.doAction = function(info){ this.doMove(); if(this.fire && fireCount == 0){ var bullet = new PlayerBullet1(); bullet.move(this.position.x + 60, this.position.y + 22); info.bullets.push(bullet); fireCount = 16; } if(fireCount > 0){ fireCount--; } } this.doMove = function(){ if((direction & 0x01) > 0){ this.dmove(3, 0); } if((direction & 0x02) > 0){ this.dmove(-3, 0); } if((direction & 0x04) > 0){ this.dmove(0, 3); } if((direction & 0x08) > 0){ this.dmove(0, -3); } } this.onDirection = function(input){ direction |= input; } this.offDirection = function(input){ direction &= ~input; } this.getRect = function(){ this.rect.left = this.position.x + 8; this.rect.top = this.position.y + 14; this.rect.right = this.position.x + 68; this.rect.bottom = this.position.y + 30; return this.rect; } } Player.prototype = new GameObject();
次にPlayerBullet1.js。これはただGameObjectを継承するようにしただけ
var PlayerBullet1 = function(){ this.position = new Point(); this.rect = new Rect(); this.life = 10000; this.damage = 100; this.score = 100000; this.doAction = function(info){ this.dmove(8, 0); } this.draw = function(context){ context.fillStyle = 'rgb(255, 255, 0)'; context.beginPath(); context.arc(this.position.x + 1, this.position.y + 1, 2, 0, 360, true); context.closePath(); context.fill(); } this.getRect = function(){ this.rect.left = this.position.x; this.rect.top = this.position.y; this.rect.right = this.rect.left + 2; this.rect.bottom = this.rect.top + 2; } } PlayerBullet1.prototype = new GameObject();
最後にEnemy1.js。描画はまた今度
var Enemy1 = function(image){ this.position = new Point(); this.rect = new Rect(); this.life = 100; this.damage = 100; this.score = 1; this.draw = function(context){ context.drawImage(image, this.position.x, this.position.y); } this.doAction = function(info){ this.dmove(-2, 0); } this.getRect = function(){ this.rect.left = this.position.x + 6; this.rect.top = this.position.y + 10; this.rect.right = this.position.x + 72; this.rect.bottom = this.position.y + 22; return this.rect; } } Enemy1.prototype = new GameObject();