Making objects face a certain object

This topic is 3744 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
Rutin
22
3. 3
4. 4
5. 5
frob
12

• 17
• 9
• 31
• 16
• 9
• Forum Statistics

• Total Topics
632617
• Total Posts
3007450

×

Important Information

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!