# How to find if an object is facing another object given position and direction as separate vectors

I found a very helpful post about exactly what I need here. It uses dot products to which is what I'm specifically looking for.

It talks about players facing monsters basically. They give a helpful picture here, My question though, is what if you have a function with 3 arguments: the position of object 1, the position of object 2, and the direction object 1 is facing given as a unit vector. So the picture would look as so: How would you find whether A is facing B?

It depends on exactly what you mean by "A is facing B", but you can use the same approach mentioned in the link you give. The other vector to examine (in addition to the direction A is facing) is the one connecting and pointing from A to B (calculated by B-A).

Your code would be something like.

facing = dotProduct(normalize(B-A), normalize(directionFacingOfA))


Which will give you the cosine of the angle between where A is facing, and the vector where A faces B. Pretty easy. Three possibilities:

1. If A faces B almost perfectly (angle close to 0), facing will be close to 1 (cos(0)).
2. If A isn't facing away from B, facing will be between 0 and 1. It is up to you to decide if this is "close enough".
3. If A is facing away from B, facing will be negative.

This approach works for either 2D or 3D.

• Oh wow, thank you. It seemed to work in my program. Question though. I've posted a link to a picture I drew. I'm not quite sure how the dot product of those two equate to which way A is facing. Could you maybe explain it a little more. i.imgur.com/8AtzUFQ.png Oct 11, 2015 at 3:13
• isn't it at (3,7)? Oct 11, 2015 at 3:22
• OH I'm sorry, I drew it wrong. Hold on Oct 11, 2015 at 3:23
• Actually, I take that back again. Yea, A is (3,7). But the direction vector is a separate argument, which would be (0,-1) Oct 11, 2015 at 3:26
• In your picture, B-A is incorrect. B-A yields a vector that if you put the tail on A, it points to B. In your picture, B-A = (2, -16), a vector pointing down and to the right. Oct 11, 2015 at 3:55