Pushing Objects in Unity
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.