Pushing Objects in Unity

Move objects in the environment

Objective: make the player able to move a box in the game.

In the scene we have a new prefab called movable box tagged as MovingBox. This object should have a rigidbody and a box collider attached.

In order to implement this feature I used the function OnControllerColliderHit() and this pseudocode explains the logic to push the box.

In the player script I declared a new variable called _pushForce, this is gonna be added to the direction when the box is being pushed. Within the OnControllerColliderHit function I created another variable to get to the rigidbody of the box. Then I checked for the MovingBox tag and added another 2 conditions.

If the rigidbody is null or kinematic then I do nothing, and if hit.moveDirection.y is less than -0.3f (which means the object is below the player) I get out of the function.

Finally I create the pushDirection vector and assign it to the rigidbody velocity multiplied by the push force.

And that’s it!!! Now the player can move the box.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rusben Guzman

A Software Engineer passionate about game dev and interactive products with Unity. I consider video games to be the artistic expression of programming.