# Making objects face a certain object

This topic is 3823 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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.

##### Share on other sites
look into atan2()

##### Share on other sites
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?

##### Share on other sites
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.

##### Share on other sites
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.

##### Share on other sites
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.

1. 1
2. 2
3. 3
Rutin
19
4. 4
khawk
14
5. 5
frob
12

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633659
• Total Posts
3013209
×