Break on Impact
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 10 of 71.
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
EasyWrite Window.cs: every hit weakens the window, and it shatters at 0.
- In the window's
OnCollisionEnter, takecollision.relativeVelocity.magnitudeoffstrength. - When
strength <= 0f, callDestroy(gameObject);.
Press Play, roll soft balls with the up arrow, then a hard one with Space: the window breaks. 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
}
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground