Using Vector3.Dot for Direction Facing Calculation

This is not a scripting question directly related to a problem, but more related to myself trying to understand the way Vector3.Dot works.

In following an example to detect if a player is facing a target, the lines of code that were used had a Vector3.Dot.

Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);

This was not explained very well as to how it was working so I decided to start digging through the net for answers. I am not totally savvy on quite a bit of math, but how this function works started becoming clearer to me as I kept searching.

I learn best with visual representations that put things into perspective, so I made this little paint drawing to understand how the Dot() works in this example.

I would very much appreciate any feedback you have if this assessment is completely wrong. I would like to understand exactly how Dot() is working and I think I have a handle on it. If this drawing is completely off though please let me know where I am thinking wrong.

Thanks!

The dot product is equal to the cosine of the angle between the two input vectors. This means that it is 1 if both vectors have the same direction, 0 if they are orthogonal to each other and -1 if they have opposite directions (v1 = -v2).

check the post of podperson here.

This doesn’t seem related to my original question but thank you for the input. This is checking to see if something is on the right or left side.

It would appear that my drawing is correct then. Thanks

The Dot product of a vector against another can be described as the ‘shadow’ of the first vector against the second one. It’sa measure of how much in alignment the first vector is to the second one.

It ranges from -magnitude to magnitude of the smaller of the two vectors.

That is, the more aligned both vectors are, the closer to Min(v1.magnitude, v2.magnitude) the result will be. 0 means you’re completely perpendicular to it (in any direction), and -magnitude means you’re facing completely away from it.

That’s how I visualize it.

For instance, I could check a character object’s transform.up vector against the absolute Vector3.up axis, to check if the character is standing up. Because those are unit vectors, the dot product will go from -1 to 1, -1 being completely upside down, 0 being laying horizontally, 1 being right-side up.

Cheers

2 Likes

Thanks HarvesteR for the response. I will keep that in mind.