Stop static colliders from overlapping

So I currently have some code through which a cube with a static collider (no rigidbody) is following the mouse in 3D space through the use of Raycasting.

The problem is, if the point is close to a wall, the collider will intersect due to the wall also being a static collider. I understand that in order for collisions to work at least one object needs to be a dynamic rigidbody, but in this instance, giving either the cube or the wall a rigidbody doesn’t make sense as I don’t want either object to interact with physics. (I know kinematic rigidbodies don’t interact with physics, but they also don’t collide with non-dynamic rigidbodies, so that doesn’t help sadly).

Is there any other way from stopping these two objects from overlapping?

Here’s a screenshot where the mouse is placed half way up a wall:
(The pivot point for the cube is in the middle, therefore it’s halfway in the wall).

This is what physics queries are for. You determine where it should collide.

Would you mind elaborating a little? My knowledge of Unity’s Physics isn’t far beyond a beginner level.

As one of your colliders is a cube (or convex MeshCollider), you may use Physics.ComputePenetration to get a better position that doesn’t overlap. ComputePenetration receives both colliders and their poses, and returns a direction and a distance to the closest non-overlapping position.

However, ComputePenetration works with a single pair of colliders. You may have the cube not to overlap the collider hit with your Raycast, but it may be overlapping other colliders (i.e. the floor in your image).

Previously to ComputePenetration you may throw a Physics.BoxCastAll query to receive all colliders that your box would collide with along the path defined by your mouse. Then you could call Physics.ComputePenetration with them, and finally apply some logic to figure out a final pose for the cube that doesn’t overlap any of them (if possible).

2 Likes

Ah, I believe after some experimentation, this can probably be used to fix the problem.
Thanks very much for the help.

1 Like