Hello,
I have 2 game objects where I would like to design a function (if there is not already one that is built-in), where the function returns -1 if both objects are facing away from each other, 0 if one object is facing the other object, while the other object is facing away, and 1 if both objects are facing directly at each other. How would I do this?
Thank you,
Michael S. Lowe
Vector3.Dot() gives you a dot product (google what that product means).
You would usually feed in whatever you consider the “forward” vector of the two objects is.
For your requirements you would need to also consider where the objects are in relation to each other and decide how close is close enough, since floating point numbers are never going to be exact.
One way is to us the delta vector between the two positions of the objects and dot that vector against each object’s “facing” vector. If you use normalized vectors for all these things then you can set arbitrary numeric thresholds from -1 to +1 and compare the dot product(s) against those boundaries to return what you want.
You might want to draw out some hard examples on paper, then feed those numbers into the code and see how dot products work to get a numeric sense of what is going on.
You could ask chat gpt?
It delivers this result:
// Function to determine facing direction
// Returns -1 if both objects are facing away from each other
// Returns 0 if one object is facing the other, while the other is facing away
// Returns 1 if both objects are facing directly at each other
public static int DetermineFacing(Vector3 obj1Pos, Vector3 obj1Dir, Vector3 obj2Pos, Vector3 obj2Dir)
{
// Normalize the direction vectors
obj1Dir.Normalize();
obj2Dir.Normalize();
// Calculate the vector from obj1 to obj2
Vector3 toOther = (obj2Pos - obj1Pos).normalized;
// Calculate dot products
float dot1 = Vector3.Dot(obj1Dir, toOther);
float dot2 = Vector3.Dot(obj2Dir, -toOther);
// Determine the facing relationship
if (dot1 > 0 && dot2 > 0)
{
return 1; // Both facing each other
}
else if ((dot1 > 0 && dot2 <= 0) || (dot1 <= 0 && dot2 > 0))
{
return 0; // One facing the other
}
else
{
return -1; // Both facing away from each other
}
}
Then again your description of the problem is not very clear. Because 2 objects “facing each other” could also mean you want to determine if an enemy sees a player, and rather would want to use some form of intersection test