2017-02-03 61 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就像我想要的那样工作! –