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?