How to detect when an object is exactly above another object?

For example when a default cube (1 x 1) is directly above another default cube (1 x 1).

It is important that the cube is exactly above it.


I have a cube moving in a direction, when it comes directly over another cube with an arrow it changes direction, so I need to detect when the cube is directly above it, then run the code to change the direction.


If it is out a bit it doesn’t stay moving along a grid, so Enter / Exit collision checks don’t work as far as I know.

Checking the distance doesn’t seem to work because of floating point imprecision.

Physics.RaycastAll has been suggested but I don’t know how to get that to ‘know’ that the cube is directly above another.


Hopefully this makes sense, any advice is appreciated.

Hello.

You have different ways to do it.

I would use Raycast or colliders to first detect top nearby objects. Then calculate the distances, but not looking for the exxact distance.

1- Detect nearby objects with colliders and OnTriggerStay

2- Calculate the Vector3 position point of what i consider tha exact “above point”

3- Calculate the distance between nearby object position and above point poistion

4- If this Vector3.distance is lower than 0.1f (for example) i consider is above.

Bye!!

Hello,
You can find this in the following ways- 1
If you want to check if ‘any’ object is near you could do two things. Either use a trigger to see when it becomes near and save a reference to this object or use Physics. OverlapSphere to find all objects within a certain range.

The best solution for your problem is a Raycast. Plus I recommend that it would be better if you have more than one raycast for check the result e.g. one from the center and two from the sides of the first object

RaycastHit hit;
if(Physics.Raycast(cube.position, Vector.up, out hit,  0.1f))
{
       if(hit.point == gameObject.tag("Tag"))
            Debug.Log("Above");

}