Rotate a sprite onto a canvas element

I have a player class with a sprite, and I want to make it face the mouse pointer.

I use this to determine if a sprite should rotate:

this.rotation = -(Math.atan2(this.x - mouseState.x, this.y - mouseState.y) * 180 / Math.PI); 

and then in my drawing method of my Player class, I do 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(); } 

he is doing something, but not what I want. The sprite seems to move wildly in a circle in the upper left corner of the canvas ( x:0, y:0 ).

How can I make a sprite face to the mouse cursor, also using its center point as a source?

+4
source share
2 answers

You do not translate back. Notice the additional call to window.ctx.translate that I added below, and pay attention to how I add a negative value for 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 does is move (translate) the center of the canvas context to the center of the object, rotate (rotate), then you need to move the center point back from what you got.

+1
source

Math.atan2 (y, x)

Note that there must first be an argument y , then x . Switch your arguments.

In addition, it returns a value in radians that you would know if you tried to call Math.atan2(1,0) . Remove the conversion to degrees.

This is the clockwise rotation measured in radians.

The point, again, is that you do not want to convert rad-hail.

 this.rotation = Math.atan2(this.y-mouseState.y, this.x-mouseState.x); window.ctx.rotate(this.rotation); 
0
source

All Articles