Question

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.

Was it helpful?

Solution

Change line

var degrees = -Math.atan2(offsetY,offsetX);      

to

var degrees = Math.atan2(offsetY,-offsetX);

Live Demo

OTHER TIPS

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.

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top