简体   繁体   中英

HTMl5 rotating sprite towards mouse coords

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> 

看起来您只需要对算法进行求逆。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM