Unity Physics: Detecting and Responding to Collisions
Collisions provide access to components on other game objects being collided with, which is very helpful when doing collision based behaviors. Let’s take a look at using Unity’s OnCollisionEnter method, as well as adding some explosion force to these barrels.
Collision Detection
This small barrel will drop down into the larger barrels below and get some information about them on collision.
The small barrel has a capsule collider, a rigidbody and a Collision Detection script.
The larger barrels are tagged with Hazard, and that is what I will use to check for them on collision.
By accessing the game object from a collision, you can grab all kinds of useful information. Here I check for the Hazard tag before sending a debug message to the console. The console will show the name of the object being collided with, as well as the position of where the initial collision occured.
public class CollisionDetection : MonoBehaviour
{
private const string _hazardTag = "Hazard";
[SerializeField] private float _explosionRadius = 5f;
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag(_hazardTag))
{
ContactPoint contactPoint = collision.GetContact(0);
Vector3 pos = contactPoint.point;
Debug.Log("Collided with " + collision.gameObject.name + " at the position of " + pos);
}
}
}
Here is the little barrel falling into the larger barrels.
The console shows the requested data.
Add Explosion Force
As a follow up to my previous article on applying forces in Unity, let’s continue on by adding some explosion force to these large barrels when the small barrel drops.
The Add Explosion Force method takes parameters for explosion power, explosion position, explosion radius, upwards modifier (for lifting objects off the ground) and a Force Mode. With no force mode set here as an optional parameter, the explosion effect does not happen.
public class CollisionDetection : MonoBehaviour
{
private const string _hazardTag = "Hazard";
[SerializeField] private float _explosionRadius = 5f;
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag(_hazardTag))
{
ContactPoint contactPoint = collision.GetContact(0);
Vector3 pos = contactPoint.point;
Debug.Log("Collided with " + collision.gameObject.name + " at the position of " + pos);
Vector3 explosionPos = this.transform.position;
Collider[] colliders = Physics.OverlapSphere(explosionPos, _explosionRadius);
foreach (Collider hit in colliders)
{
if (hit.TryGetComponent(out Rigidbody rb))
if (rb != null)
rb.AddExplosionForce(10f, explosionPos, _explosionRadius, 3.0F, ForceMode.Impulse);
}
}
}
}
Here is the final explosion in all of it’s physics based glory.
I hope you enjoyed this brief dive into collisions and explosion forces, and thanks for reading!