2
\$\begingroup\$

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, enter image description 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:

enter image description here

How would you find whether A is facing B?

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – Andrew Tsay Oct 11 '15 at 3:13
  • \$\begingroup\$ isn't it at (3,7)? \$\endgroup\$ – Andrew Tsay Oct 11 '15 at 3:22
  • \$\begingroup\$ OH I'm sorry, I drew it wrong. Hold on \$\endgroup\$ – Andrew Tsay Oct 11 '15 at 3:23
  • \$\begingroup\$ Actually, I take that back again. Yea, A is (3,7). But the direction vector is a separate argument, which would be (0,-1) \$\endgroup\$ – Andrew Tsay Oct 11 '15 at 3:26
  • \$\begingroup\$ 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. \$\endgroup\$ – Steven Hansen Oct 11 '15 at 3:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.