在画布元素上旋转精灵

5

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

我使用以下方法来计算精灵的旋转角度:

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个回答

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();
}

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


0

Math.atan2(y,x)

请注意,y 参数先出现,然后是 x。交换参数的位置。
此外,它返回一个弧度值,如果您尝试调用 Math.atan2(1,0),就会知道这一点。删除角度转换。

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

意思是,再次强调您不需要进行弧度-度转换。
this.rotation = Math.atan2(this.y-mouseState.y, this.x-mouseState.x);

window.ctx.rotate(this.rotation);

精灵没有因为没有将其转换为度数而疯狂旋转,但它仍然在画布的左上角周围大圆圈旋转。 - James Dawson
1
你需要先进行“旋转”,然后再进行“平移”。 - Niet the Dark Absol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接