Question

I have a fiddle here. What i am asking is that the space ship must be facing the direction of movement because it would not make sense not to. Anyway i think the problem i am having is to find a angle and have the ship rotate by that angle when the ship moves somewhere differently.

function draw () { //Create and animates 
var angle = Math.atan2(clickedChords.y - player.y, clickedChords.x - player.x);
 ctx.clearRect(0,0,canvas.width,canvas.height);  

  ctx.fillStyle= 'white'; 
  ctx.beginPath();
  //Creates crossHair/nav marker
  ctx.arc(clickedChords.x,clickedChords.y,3,0,360);
  ctx.rect(clickedChords.x - 8,clickedChords.y - 1,16,2);     
  ctx.fill();

  ctx.drawImage(ships.blueBeginers,player.x-15,player.y-15);  

  player.x += Math.cos(angle); 
  player.y += Math.sin(angle);

  requestAnimationFrame(draw); //God  
  }
 draw();

I am having a problem also translating the image and then rotating from the middle of the image. It could be something simple but i am stuck.

Thank you for helping me.

Was it helpful?

Solution

  • You need to translate the canvas to the center point at which you will do the rotation
  • Rotate based on the angle you have
  • Draw image
  • Reset transformation

In code it would be these lines:

 ctx.translate(player.x, player.y);    // translate to center of rotation
 ctx.rotate(angle + 0.5*Math.PI);      // rotate, here +90deg to comp image dir.
 ctx.translate(-player.x, -player.y);  // translate back
 ctx.drawImage(ships.blueBeginers,player.x-15,player.y-15);  // draw image
 ctx.setTransform(1,0,0,1,0,0);        // reset transforms (identity matrix)

FIDDLE

The flickering is because you calculate the atan2 angle each frame. When position equals click position you will have atan of a very small value toggling due to the adding of cos/sin later.

You can fix this by caching the angle on your click object as in this version:

FIDDLE fixing flicker

However, you need a conditional check to stop animating as now you just add the values from cos/sin and nothing is stopping it (here is one way of doing it).

Tip 1: Create the image of the ship facing right. This would correspond to 0° and save you from adding 90° each time.

Tip 2: Cache the angle value and calculation once then you don't have to calculate atan2/cos/sin each time as they are relative expensive operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top