3D Vector (X, Y, Z) look at Vector

2019-05-23 03:34发布

问题:

Im working with the source sdk (Which uses c++) and I want to rotate a entity's angle so it looks at another entity.

A entity can be looked at as a gameobject or similar and has a position (Vector) in the world as well as a angle (Vector).

I can rotate the entity by using SetAbsAngles which takes a QAngle (Basically a Vector) as parameter.

回答1:

Here is some pseudo-code:

vec3 p = entity2->getPosition();
vec3 r = entity1->getPosition();
float xdistance = p[0] - r[0];
float ydistance = p[1] - r[1];
float zdistance = p[2] - r[2];
float xzdistance = sqrt(xdistance * xdistance + zdistance * zdistance);
entitity1->setHeading(atan2(xdistance, zdistance)); // rotation around y
entitity1->setPitch(-atan2(ydistance, xzdistance)); // rotation around x
entitity1->setBank(0); // rotation around z

The z-rotation is set to 0 because it cannot be determined. You can set it freely if you like.

This works in a coordinate system with z facing forward, y up and x to the right. If you are using a different system you may have to adjust some signs.