2017-02-03 60 views
1

我正在使用HTML5 Canvas和JavaScript進行遊戲。這是一個簡單的太空射擊遊戲,在屏幕中央有一個大炮。我可以旋轉大炮並以與大炮方向相同的角度發射導彈。以任意角度移動移動對象上的X和Y起點

但我有一個問題。對於導彈X和Y的起點,我使用大炮的X和Y位置。這看起來很奇怪,因爲我想讓導彈從大炮外面開始,就像角度方向上的50個像素一樣。我如何計算?

有了這個代碼創建導彈對象:

var dX = Math.cos(this.playerRotationAngle * Math.PI/180); 
var dY = Math.sin(this.playerRotationAngle * Math.PI/180); 
this.activeMissilesArray.push(new Missile(cannon.posX, cannon.posY, dX, dY)); 

這是從導彈對象的構造函數其中I計算的方向:

this.directionX = dX * this.speed; 
this.directionY = dY * this.speed; 

Draw方法:

Draw: function(context) 
{ 
    context.drawImage(this.missile, this.posX-20, this.posY-20); 
} 

更新方法:

Update: function() 
{ 
    this.posX += this.directionX; 
    this.posY += this.directionY; 
} 

回答

1

您是否嘗試過使用速度公式以50的值來調整初始位置?

// inside the Missile constructor 
// instead of: 
// this.posX = x; 
// this.posY = y; 
// do: 
this.posX = x + 50 * dX; 
this.posY = y + 50 * dY; 
+0

嗨!感謝您的回答!這工作完美!我只是嘗試了this.posX = x + 50而不使用* dX,但使用* dX就像我想要的那樣工作! –