Jam*_*son 5 javascript html5 canvas
我有一个带有精灵的玩家类,我想让它面向我的鼠标指针.
我正在使用它来计算精灵的旋转应该是什么:
this.rotation = -(Math.atan2(this.x - mouseState.x, this.y - mouseState.y) * 180 / Math.PI);
Run Code Online (Sandbox Code Playgroud)
然后在我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();
}
Run Code Online (Sandbox Code Playgroud)
它做了一些事情,但不是我想要的.精灵似乎围绕画布的左上角旋转了一圈(x:0, y:0).
如何将精灵面朝向鼠标光标,同时使用其中心点作为原点?
你不翻译回来。请注意我在下面添加的额外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();
}
Run Code Online (Sandbox Code Playgroud)
基本上,它所做的是将画布上下文中心移动(平移)到对象中心,旋转(旋转),然后您需要将中心点从您获得它的位置移回。