Reputation: 6662
I have a rocket that is following the mouse with a slight delay in my canvas, and I want it to point towards the mouse while it's traveling around. I have almost gotten it, as you can see in my fiddle HERE. My problem is that the rotation is kind of opposite of the direction I want it to be, and it's just weird and jiggely.
The JS i'm using to get it to do so in my canvas is:
ctx.save();
var offsetY = targetToGo.x - shape.y ;
var offsetX = targetToGo.y - shape.x ;
var degrees = -Math.atan2(offsetY,offsetX);
ctx.translate(shape.x, shape.y);
ctx.rotate(degrees);
ctx.drawImage(shape.image,-shape.image.width/2,-shape.image.width/2);
ctx.restore();
Is it the canvas code or the math that is wrong? I'm bad at both.
Upvotes: 1
Views: 1408
Reputation: 2202
Calculate the offset like this.
var offsetY = targetToGo.x - shape.x ;
var offsetX = targetToGo.y - shape.y ;
And apply this rotation.
ctx.rotate(degrees+Math.PI);
Upvotes: 0
Reputation: 35309
Change line
var degrees = -Math.atan2(offsetY,offsetX);
to
var degrees = Math.atan2(offsetY,-offsetX);
Upvotes: 3
Reputation: 1257
The math is wrong. Negating offsetY and offsetX will fix it.
var degrees = -Math.atan2(-offsetY, -offsetX);
Also the angle is not in degrees but radians.
Upvotes: 0