time and space

time and space

  • 1.4k
  • 31
  • 57.1k

Making a moving missile sprite face the player (2D)

Apr 6 2012 6:01 AM
I have the following code in my Update method which makes a missile follow the player around the screen using a normalised vector:

if ((missile.eventElapsed += gameTime.ElapsedGameTime) >
  missile.eventInterval)
{
  //Get the normalised vector pointing from missile to player,
  //so missile seeks player.
  missile.directionVect = playerPosition - missile.position;
  missile.directionVect.Normalize();

  //Get the rotation angle (used later in the render method).
  missile.rotation =
  (float)(Math.Atan2(missile.position.Y - playerPosition.Y,
  missile.position.X - playerPosition.X)
  + Math.PI / 2);

  //Update the missile position so it seeks the player.
  missile.position += missile.directionVect * missile.velocity;
}  

However, there are two problems.  The first is that when the missile rotates as it follows the player, the sprite "flips" into position, rather than rotating smoothly and gradually.  The second problem is that the missiles are following the player from the wrong end - the tail end faces the player instead of the nose end.  The missiles are always launched facing upwards before the above routine takes over.  Does anyone have any ideas how I might alter the routine to fix these issues?