I have a player class with a sprite and I want to make it face towards my mouse pointer.
I'm using this to work out what the rotation of the sprite should be:
this.rotation = -(Math.atan2(this.x - mouseState.x, this.y - mouseState.y) * 180 / Math.PI);
and then in my draw method of my Player
class I'm doing this:
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();
}
it does something, however not what I want. The sprite seems to move wildly in a circle around the top left of the canvas (x:0, y:0
).
How can I make the sprite face towards the mouse cursor, also using its centre point as the origin?
You're not translating back. Note the extra window.ctx.translate
call I added below, and notice how I've add negative to both the x and y values.
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();
}
Basically, what this is doing is moving (translating) the canvas context center to your object center, rotating (rotate), then you need to move the center point back from were you got it from.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With