Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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
add comment

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

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

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
add comment

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
add comment

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