Rigidbody Physics: Collisions and Triggers
Unity's physics engine moves and collides GameObjects for you, once they have a Rigidbody (3D) or Rigidbody2D (2D) component and a Collider.
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed = 20f;
void Start()
{
GetComponent<Rigidbody>().linearVelocity = transform.forward * speed;
}
void OnCollisionEnter(Collision collision)
{
Debug.Log($"Hit {collision.gameObject.name}");
Destroy(gameObject);
}
}
Collisions vs triggers
- A regular collision (
OnCollisionEnter/Stay/Exit) needs both objects to have solid (non-trigger) colliders, physics stops them from overlapping. - A trigger collider (
Is Triggerchecked) lets objects pass through it, but still firesOnTriggerEnter/Stay/Exit, useful for pickups, checkpoints, or damage zones that shouldn't physically block anything. - Both events only fire if at least one of the two objects also has a
Rigidbody.
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Player entered the zone");
}
}
Physics update, not Update
Move a Rigidbody with Rigidbody.linearVelocity or AddForce inside FixedUpdate(), not Update(), FixedUpdate runs on physics's fixed timestep, keeping movement consistent regardless of framerate.