OnTriggerEnter is not always working properly

I have a box collider around my camera, which is a trigger that is supposed to detect if the camera is close to the terrain. Most of the time it works, but sometimes the bool is set to ‘false’ even though the trigger is IN the collider(terrain). This happens because the ‘OnTriggerExit’ is the last thing that was called, which I’m not really sure how or why it happens.

Here is the code:

public CameraController camController;

private void OnTriggerExit(Collider other)
{
    camController.isColliderTouching = false;
}
private void OnTriggerEnter(Collider other)
{
    camController.isColliderTouching = true;
}

Now I did try replacing the ‘OnTriggerEnter’ with ‘OnTriggerStay’ AND even having both at the same time, but it didn’t resolve the issue. Somehow, it still manages to ignore(?) it at times.

I also tried changing the collision detection method on the collider, but unfortunately that did not work out either.

Make sure every physics operation is performed with rigidbody inside FixedUpdate. Only when applying forces you can get a precise simulation, MovePosition and friends are teleportation and can skip triggers.

I made sure to move the collider using FixedUpdate instead of just parenting under the camera and turned the rigidbody interpolation (also tried extrapolation) on for the collider.

private void FixedUpdate()
{
    transform.SetPositionAndRotation(mainCam.transform.position, mainCam.transform.rotation);
}

This seemed to do the trick for a while, but while it IS happening less now, the issue still persists and occasionally skips triggers.

That’s teleportation. Use Rigidbody instead of Transform. And the only way to really avoid teleportation is adding forces with Rigidbody methods:

In the documentation it says MovePosition creates a smooth movement when interpolation is enabled, therefore it’s not teleportation, right?

Ok, that seems right.

1 Like