Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating a sprite on a canvas element

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?

like image 289
James Dawson Avatar asked Nov 03 '22 04:11

James Dawson


1 Answers

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.

like image 152
Jarrod Avatar answered Nov 09 '22 14:11

Jarrod