C++ dot product to get if one object is in front of another?

Viewed 127

Im trying to use Vector2::Dot and Math::Acos to determine whether one gameobject is in front of another. With what I have, I'm able to get whether the first object's forward vector is at a perpendicular angle to second actor's forward vector:

float dotResult = Vector2::Dot(GetForwardDir(), secondActor->GetForward());
float angle = Math::Acos(dotResult);
    
if(angle <= minAngle)
    //do something

Where GetForwardDir() is:

return Vector2(Math::Cos(mRotation), -Math::Sin(mRotation));

However this does not account for where the second actor is relative to the first actor. I don't think Im understanding something here about dotResult and the Acos angle.

How can I use this to get whether the first actor is in front of the second?

1 Answers

You probably want a cross product for this. The dot product will give you a scaled cos for the angle between two vectors. A cross product will give you the sin, which is more useful here.

Basically, make two vectors:

  • ActorA position + ActorA.Forward vector
  • ActorA position + (ActorB.position - ActorA.position)

Or, just

  • ActorA.forward X normalize(ActorB.Position - ActorA.position);

Since you're doing this in 2D, the result will be a scalar. If the sign of the result is positive, then ActorB is within 180º (+- 90º) of ActorA's forward vector, from ActorA's position.

Technically, you're calculating an orthogonal vector, the Z component of which will tell you if the target is in front of or behind the viewer, but the X and Y components of that vector are zero, because orthogonal.

Purists will say that the cross product does not exist in 2D, and they're technically correct, but this is how it's done.

Related