Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

I've beeen going through Reimer's flightsim tutorial and wanted to expand it by adding anti air turrets shooting at the ship. Im still new to programming in c# and xna and also a bit horrible in maths :P. How would I go about calculating how the turret would track the ship which is moving in 3 axes? Looking through the tutorial I assume I'll be using a quaternion and using lerp to try and smooth the tracking movement?

My model is just a simple hovering ball with a gun so theres no animation or bones to worry about.

share|improve this question

marked as duplicate by Byte56, Trevor Powell, bummzack, Sean Middleditch, Josh Petrie Mar 22 '13 at 15:14

This question was marked as an exact duplicate of an existing question.

up vote 0 down vote accepted

Quaternion is the right keyword! Look at this question which deals with the same problem.

Basicly your objects have a position and an orientation. To point the turret at the ship you need to find the vector pointing from turret to ship. Then you can manipulate the turret to point at the ship and start you shoot logic / animation.

share|improve this answer
Argh forgot about the need to slerp in this case. Use this skon. – indeed005 Mar 18 '13 at 12:54
Followed the link, implemented the suggested code and it works perfectly. Thanks floAr. – skon Mar 18 '13 at 14:13

You could use a "LookAt" view matrix for the World transform of the turret.

See Matrix.CreateLookAt

This method requires you to figure out the Up vector though. The cross product of two perpendicular vectors will give you the third perpendicular vector in the direction of the handedness of the system.

///  position = my position, lookat = the position of the object I want to look at
public static Matrix LookAt(Vector3 position, Vector3 lookat)
    Matrix rotation = new Matrix();

    rotation.Forward = Vector3.Normalize(lookat - position);
    rotation.Right = Vector3.Normalize(Vector3.Cross(rotation.Forward, Vector3.Up));
    rotation.Up = Vector3.Normalize(Vector3.Cross(rotation.Right, rotation.Forward));

    return rotation;
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.