0
votes

I'm trying to rotate a sprite towards mouse position, but I just fail at figuring out the proper way to to calculate the angle. The ship is always facing wrong direction.

angle = Math.atan2( ship_coords[0] - e.clientX ,ship_coords[1] -  e.clientY  );

Please see the below example:

var c=document.getElementById("myCanvas");
	var ctx=c.getContext("2d");
	
	var ship = new Image();
	var ship_coords = [c.width/2, c.height/2]
	
	ship.onload = function(){
		window.requestAnimationFrame(draw);
	}
	
	ship.src = "http://pixeljoint.com/files/icons/spaceship.png";
	
	var TO_RADIANS = Math.PI/180; 
	var angle = 0;
	
	c.addEventListener("mousemove", function(e){
		angle = Math.atan2( ship_coords[0] - e.clientX ,ship_coords[1] -  e.clientY  );
	})
	

	function draw(){
		ctx.clearRect( 0,0,c.width,c.height );
		ctx.save(); 
		ctx.translate( ship_coords[0], ship_coords[1] ); //// align to center ///
		ctx.rotate( angle );
		ctx.drawImage( ship, -(ship.width/2), -(ship.height/2) ); //// set center of the image ////
		ctx.restore();
		window.requestAnimationFrame( draw );
	}
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
	  #myCanvas {
		border: 1px solid #000;
		width: 578px;
		height: 200px;
	  }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
  </body>
</html>
1

1 Answers

0
votes

It looks like you just need to invert the arithmetic.