How to find which faces of objects are facing with others in 3D

Hi,

I would like to know is there any method to solve this problem:

let say i have two objects A and B in 3D (in this case cube A and cube B). How can i find which face of object A are facing a face of object B?

In case my sentences are not clear, please refer to the image that i have attached. based on the image that i have attached, how can we find that the blue face of object A is facing the red face of object B?

[21175-facing+object+in+3d.jpg|21175]

Thanks for your help.

Say you have two transforms for the two objects. You can calculate a normalized vector from A to B with:

var toB = (objectB.position - objectA.position).normalized;

Now you can compare either the Vector3.Angle() or the Vector3.Dot() of all six sides of objectA with toB. The one with the lowest angle or the one with the highest dot product will be the side facing B. For example if you were testing the dot product you would look at:

  • Vector3.Dot(toB, objectA.forward)
  • Vector3.Dot(toB, -objectA.forward);
  • Vector3.Dot(toB, objectA.right);
  • Vector3.Dot(toB, -object.right);
  • Vector3.Dot(toB, objectA.up);
  • Vector3.Dot(toB, -ObjectA.up);

For the second cube, it is the same process but the test vector is reversed:

var ToA = -ToB;

Note you can simplify your logic some by putting the six world directions (Vector3.right, Vector3.left, Vector3.up, Vector3.down, Vector3.forward, Vector3.back) into an array and use Transform.TransformDirection() to calculate the directions for each object. Or if the objects are never rotated, then you can use these without Transform.TransformDirection(). Anyway, putting them into an array just makes the code simpler.

@robertbu how can i? detect a single objects face,
for example lets say that i want to be on specific face of a cube, how can i mention that cube. and how can i recognize the face of a object that im on (the cube of my 3d character is on)?