Physics.Raycast() not working correctly on gameobject moved with transform.Translate()

I am playing around in Unity trying to make my own simple collision system using Physics.Raycast() to determine whether a collision has occurred. I have a cube primitive with a box collider from which I cast raycasts every frame. I am moving my box around using transform.Translate(velocity).

Here is the code on the box which deals with the collisions moving in the positive x-axis direction:

if (Physics.Raycast(r, out hit, rayLength, obstacleMask)) {

Vector3 newPos = transform.position + velocity * Time.deltaTime;

if ((newPos.x - transform.position.x) > hit.distance)  velocity.x = 0;
               
}

I am checking collisions before I move the box and if collisions occur velocity.x = 0 which stops the box.
Now, if ((newPos.x - transform.position.x) > hit.distance is checking whether the change in distance of my next step will be greater than the distance between the exterior of my box with the colliding object. As such, this should prevent the box from ever overshooting the collider. However, this is not so. At certain frames I am able to completely travel through the collider.

Why is this so? There must be a problem with Physics.Raycast() which fails with moving objects but I cannot figure out why exactly. Is this a known thing?

1 Like

Here is a video to show you what I mean. Most of the times the Raycast works but occasionally the box will just go through the collider.

It could be that you’re casting from the inside of the collider.
(When too close, ray may start inside of the collider, ignoring it completely)

The solution to that is to offset the raycast origin position by a little bit of margin. Like 0.01f;