How to match two cubes

Hello everybody,

I’m new for Unity3D and trying to master scripting.
I have one stationary cube game object. Another one is moving. Cubes have very similar size (very close but not exactly the same).The goal is to move mobile cube to match with stationary one. What is best approach to detect this match? Compare position and rotation in OnCollisionEnter event? Or see if all eight cubes points are in the proximity? Or something else?

You could do collision/trigger if you made the box very small in the center of each cube, I presume. :slight_smile:
You could use this method:

And check for a very close (but not exact) distance.

Those are a couple of ideas that come to mind.

If these were spheres, you’d check the distance between the centers of the spheres, and compare their radii (to see if they’re the same size and in the same position)

You can extend that idea to these cubes by checking distance between positions, and size (height and diagonal distance between opposite corners).

If rotation is a factor, then probably the easiest way is to create a new AABB box that encapsulates all points for each cube, then run the same tests on those.

I use Vector3.Distance to see how close centers of the cubes are. But it doesn’t count orientation.
Playing with rotation now. The idea is if positions are close and rotations are similar then cubes match each other.

Boxes have virtually the same dimensions x y z. But each try they are different for both boxes. They are cuboids (parallelepipeds mathematically speaking) but straight cubes. Both of them have box collider of course. So colliders have AABB (bounds). The orientation has to be the same from box perspective (“top” to face up and “bottom” to face down are not important). Not sure how extra AABB can help with orientation. Could you please elaborate on this?

I have resolved it by making box collider of the stationary box slightly bigger then visual size. The I check if all vertices of the mobile box are inside stationary one’s collider. Works well. Below is code snippet

private bool IsMatched(Collider other)
{
Bounds bounds = GetComponent().bounds;
Vector3 vertices = other.GetComponent().mesh.vertices;
Transform tr = other.GetComponent();
foreach(Vector3 v in vertices)
{
Vector3 wp = tr.TransformPoint(v);
if(!bounds.Contains(wp))
{
return false;
}
}
return true;
}

1 Like