In this lesson, you will learn how to make your player character physically nudge or push lightweight objects, such as crates or barrels, as they walk into them.
The Physics of Pushing
When a character walks into a physics object, the object often doesn't move because the character’s Rigidbody is either kinematic or too heavy. To create a natural interaction, we leverage the OnControllerColliderHit method. This built-in Unity event triggers whenever your character controller strikes a collider while moving.
Implementing the Push Force
Instead of writing complex custom physics code, we can check if the object we hit has a Rigidbody component. If it does, we apply a force to it based on the character’s movement direction.
Here is how you implement this in your movement script:
void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
// Check if the object has a Rigidbody and isn't kinematic
if (body != null && !body.isKinematic)
{
// Calculate the push direction (ignore vertical force to prevent tipping)
Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
// Apply an impulse force to the object
body.AddForce(pushDir * pushForce, ForceMode.Impulse);
}
}
Why This Works
By isolating hit.moveDirection to only the X and Z axes, we ensure the player doesn't "launch" items into the air just by walking into them. The pushForce variable acts as a multiplier—you can adjust this value to make heavy objects feel immovable and lighter objects feel responsive.
Because you have already learned about Physics Materials and Friction, remember that the object’s Drag and the material’s Dynamic Friction will significantly affect how the object behaves after you push it. A crate with high friction will stop almost immediately, while one with low friction will slide across the floor. This integration turns your static environment into a tactile playground, making the world feel tangible rather than just a painted backdrop.
Key Takeaway: By utilizing the OnControllerColliderHit event to apply an impulse to an object's Rigidbody, you can seamlessly translate character movement into interactive world-physics.