以任意角度移动移动物体上的X和Y起点

时间:2017-02-03 21:45:22

标签: javascript html5 html5-canvas

我正在使用HTML5 Canvas和JavaScript开发游戏。它是一个简单的太空射击游戏,在屏幕中央有一门大炮。我可以用与大炮方向相同的角度旋转大炮和发射导弹。

但我有一个问题。对于导弹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));

这是来自导弹对象的构造函数,我计算方向:

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 个答案:

答案 0 :(得分: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;