我有一个带有 Sprite 的玩家类,我想让它面向我的鼠标指针。
我用它来计算 Sprite 的旋转应该是什么:
this.rotation = -(Math.atan2(this.x - mouseState.x, this.y - mouseState.y) * 180 / Math.PI);
然后在我的 Player
类的 draw 方法中我这样做:
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();
}
它做了一些事情,但不是我想要的。 Sprite 似乎在 Canvas 左上角的圆圈中疯狂移动 (x:0, y:0
)。
如何让 Sprite 面朝鼠标光标,同时使用它的中心点作为原点?
最佳答案
您没有回译。请注意我在下面添加的额外 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();
}
基本上,这是在将 Canvas 上下文中心移动(平移)到您的对象中心,旋转(旋转),然后您需要将中心点从您获取它的位置移回。
关于javascript - 在 Canvas 元素上旋转 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14947777/