Platformer: Pushing The Box
In this article, we will cover how to give the player the ability to push a box by running into it. This will translate to create a pressure plate feature that will unlock a new part of the level when the box is pushed on it.
When creating the box that will be pushed, we need to create and add a tag “Moving Box” to identify it when the player collides with it. We will also have to add a Rigidbody, so we can add velocity to it.
In the OnControllerColliderHit on the player script, the hit variable stores the other object the player controller collider runs into, so we can check the tag of this object to identify different objects. In this case, we check to see if it is the “Moving Box”, and if it is we want to get the Rigidbody of the box and store it in a local variable box. We must perform a null check to make sure there is a Rigidbody to prevent the code from breaking.
In giving the box a velocity, we need two things; direction and speed. For the direction we create a local Vector3 variable pushDir and set it to the direction it is being pushed on the x-axis. We will want to zero out the y and zedd because we only want it to move left or right. We can give the box a velocity since it has a Rigidbody, by multiplying it be the pushDir with a global variable we create called _pushPower, which is the speed.
Fixing the Box
The box is rotating as it is being pushed, which is fine, but we want it to slide, so we
We can freeze the rotation on x, y, z axis, so it will no longer tumble but slide.