Making objects face a certain object

Started by
4 comments, last by Trienco 15 years, 10 months ago
Lets say I have an object the player controls, and I want other objects to always look at it, meaning, rotate them to face it, how would I do that? Thanks.
Advertisement
look into atan2()
How you would do so depends on a number of different factors. Is your game 2D or 3D? Do you want the rotation to occur from each object's basal orientation or from the object's current orientation? Do you want to restrict rotations to be about an object rotation axis or be a free rotation?
Sorry for the lack of info, my game is 3d.
The player controls an object and is able to rotate it around Y axis (turn left,right) and is able to strafe with it. Movement is restricted to the xz plane.
I want other objects to always 'look at' the object controlled by the player.

Thanks in advance.
If you're basically trying to solve a 2-d problem, you can use atan2(), as noted previously:
vector3 diff = player.position - npc.position;float y_angle = atan2(diff.z, diff.x);
You may need to modify the return value of and/or the arguments to atan2(), depending on the conventions that you're using.
As you said you're technically in 3D, why don't you just plug the right values into the matrix? Obviously you know the position (4th vector in matrix) and the unused direction (y = 2nd vector). You also know z (3rd vector, assuming your unrotated objects face z, replace with x otherweise).

So:
Vector z = (player.pos- object.pos).normalize;

For the other vector you don't even need a crossproduct in 2D, just swap the variables and flip one sign (depending on handedness, just try until it's right or look up how the rotation matrix is built to see why)

Resulting matrix as array[16]:

z.z, 0, -z.x, 0,
0, 1, 0, 0,
z.x, 0, z.z, 0,
pos.x, pos.y, pos.z, 1

No trig, no fancy math, just one lousy vector subtraction and a normalization.


Of course, if your player can move so fast, that you need to actually animate the rotating, this would only give you the target orientation and just linearly interpolating matrices isn't really going to work.
f@dzhttp://festini.device-zero.de

This topic is closed to new replies.

Advertisement