在画布元素上旋转精灵

时间:2013-02-19 00:26:36

标签: javascript html5 canvas

我有一个带有精灵的玩家类,我想让它面向我的鼠标指针。

我正在使用它来计算精灵的旋转应该是什么:

this.rotation = -(Math.atan2(this.x - mouseState.x, this.y - mouseState.y) * 180 / Math.PI);

然后在我的Player课程的绘制方法中,我正在这样做:

Player.prototype.draw = function() {
    window.ctx.save();
    window.ctx.translate(this.x + this.sprite.width / 2, this.y + this.sprite/height / 2);
    window.ctx.rotate(this.rotation);
    window.ctx.drawImage(this.sprite, this.x, this.y);
    window.ctx.restore();
}

它做了一些事情,但不是我想要的。精灵似乎围绕画布的左上角(x:0, y:0)疯狂地移动。

如何将精灵面朝向鼠标光标,同时使用其中心点作为原点?

2 个答案:

答案 0 :(得分:2)

你没有翻译。请注意我在下面添加的额外window.ctx.translate调用,并注意我如何为x和y值添加负数。

Player.prototype.draw = function() {
    window.ctx.save();
    window.ctx.translate(this.x + this.sprite.width / 2, this.y + this.sprite/height / 2);
    window.ctx.rotate(this.rotation);
    window.ctx.translate(-this.x + this.sprite.width / 2, -this.y + this.sprite/height / 2);
    window.ctx.drawImage(this.sprite, this.x, this.y);
    window.ctx.restore();
}

基本上,这样做是将画布上下文中心移动(平移)到您的对象中心,旋转(旋转),然后您需要从中心点移回中心点。

答案 1 :(得分:0)

  

Math.atan2(Y,X)

请注意,y参数首先出现,然后 x。切换你的论点。

此外,它还会返回一个以弧度为单位的值,如果您尝试调用Math.atan2(1,0),则会知道该值。删除转换为度数。

  

这是以弧度为单位的顺时针旋转

意思是,你不想要你的rad-deg转换。

this.rotation = Math.atan2(this.y-mouseState.y, this.x-mouseState.x);

window.ctx.rotate(this.rotation);
相关问题