I have a particular scenario where I want to use a trigger to adjust the course of a fast-moving projectile, but am running into issues because Unity does not support continuous collision detection for triggers.
Imagine we have a thin wooden door. We want a bullet to be able to pass through the door, but the bullet's velocity should be reduced and trajectory altered when this occurs. We might put a trigger collider on the door, with some code like this:
void OnTriggerEnter(Collider other) {
if (other.tag == "Bullet") {
Rigidbody body = other.GetComponent<Rigidbody>();
body.velocity = body.velocity * .75f;
float maxRot = 45;
float rx = Random.Range(-maxRot, maxRot);
float ry = Random.Range(-maxRot, maxRot);
Quaternion rotationChange = Quaternion.Euler(new Vector3(rx, ry, 0));
body.velocity = rotationChange * body.velocity;
transform.LookAt(transform.position + body.velocity.normalized);
}
}
The problem is that Unity does not support continuous collision detection for triggers. If the bullet is moving fast, the trigger effect may not be applied until the bullet is well past the door (it seems to get applied a frame late), or the bullet may pass from one side of the trigger to the other without ever touching the trigger.
Changing the Rigidbody collision detection mode (e.g. "continuous", "continuous dynamic") has no effect on triggers. I've already tried every combination of collision detection modes on both the bullet and the door.
I'm hoping for a good workaround that does not carry a high performance cost. Solutions I've considered:
- Increase the FixedUpdate frequency dramatically (expensive)
- Use raycasts to simulate continuous collision detection (could get expensive with lots of bullets)
- Use a thicker trigger collider on the door (helps, but does not eliminate the issue, and gives an inconsistent experience with different speeds of bullets)