# Angle between two 3d Vectors

## Recommended Posts

Pombal    280
Hi!
I'm trying to make an object "look at" another given they're translation vectors.

The way I'm doing it now is this:

Vector3 own = owner->getTransform().getTranslation();own.normalize();Vector3 tar = target->getTransform().getTranslation();tar.normalize();float angle = Math::acosF(own.dot(tar));Vector3 axis = own.cross(tar);axis.normalize();glRotatef(Math::radToDeg(angle), axis.X(), axis.Y(), axis.Z());

The results are not what you would expect and I was hoping you could help me figure out why. If you need more information just ask. Thanks!

##### Share on other sites
grhodes_at_work    1385
The translation vectors are not what you want to be using here. The translation vectors correspond to the location of the objects, not where they are looking. You need to pull one of the columns out of the rotation matrix of the transform. (a column or a row of the rotation part of the transform depending on your API.) So, instead of owner->getTransform().getTranslation(), I imagine you'd have something like owner->getTransform().getRotation().getLookAt(), or perhaps owner->getTransform().getRotation().GetZAxis()...or something along those lines depending on your API (and GetX/GetY/GetZAxis depending on which of those object space axes represents the direction being looked in).

I am also concerned with the code you posted. You are using a library (a C++ library?) to represent your objects and you are using state properties stored in those objects to determine the angle change. BUT, you have called an OpenGL function directly to apply the rotation. I do not see where you set the updated orientation on the "owner" object. Without something else...your code objects aren't going to track what you render.

I hope that helps!

##### Share on other sites
Pombal    280
Ha, thanks, that clarifies things!

As for the library, yes, it's c++ and its custom made. The state of the objects is managed by using glGetFloatv to pass the ModelViewMatrix to the objects.