javascript - Rotating a sprite on a canvas element -
i have player class sprite , want create face towards mouse pointer.
i'm using work out rotation of sprite should be:
this.rotation = -(math.atan2(this.x - mousestate.x, this.y - mousestate.y) * 180 / math.pi);
and in draw method of 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 something, not want. sprite seems move wildly in circle around top left of canvas (x:0, y:0
).
how can create sprite face towards mouse cursor, using centre point origin?
you're not translating back. note window.ctx.translate
phone call added below, , notice how i've add together negative both x , 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, doing moving (translating) canvas context center object center, rotating (rotate), need move center point got from.
javascript html5 canvas
No comments:
Post a Comment