Menu
CoddyTech

Break on Impact

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 10 of 63.

How hard was the hit? collision.relativeVelocity is how fast the two objects were closing in on each other at the moment they met, and its magnitude is the impact speed in m/s. It is a difference of velocities: a car at 10 m/s that runs into a car going the same way at 8 m/s hits at only 2 m/s, and both cars see the same impact speed.

This egg breaks when it lands faster than crackSpeed. Dropped from 1 m it hits at about 4.4 m/s (the square root of 2 x 9.81 x 1), and from 2 m at about 6.3 m/s:

public float crackSpeed = 5f;

void OnCollisionEnter(Collision collision)
{
    if (collision.relativeVelocity.magnitude > crackSpeed)
    {
        Debug.Log("Splat!");
        Destroy(gameObject);
    }
}

Why not the egg's own rb.linearVelocity? By the time OnCollisionEnter runs, physics has already handled the hit, so the egg's velocity is what is left after it, close to zero. relativeVelocity keeps the speed of the impact itself. It is a speed, so mass plays no part: a heavy egg and a light one landing at 6 m/s report the same 6.

challenge icon

Challenge

Easy

The ball rolls at the window: the up arrow rolls it softly, Space rolls it hard (Bowler.cs, already written). Write Window.cs. The window has a strength (10 in the Inspector).

  • Every hit weakens the window by its impact speed: a hit at 2 m/s takes 2 off strength.
  • When strength reaches 0 or less, the window shatters: destroy the window.

Press Play, roll a few soft balls and then a hard one, then Check.

Try it yourself

using UnityEngine;

public class Window : MonoBehaviour
{
    public float strength = 10f;

    // Every hit takes its impact speed off strength; at 0 the window shatters
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay