Pushing Objects in Unity to Complete Puzzles
This article will show how to create a Box that the Player can push to complete puzzles.
The Box that the Player will push is a cube with a Box Collider and Rigidbody. The Rigidbody will allow the Player to apply velocity to it. The Rotation and z-axis Movement constraints are frozen to prevent the Box from rotating and moving on the z-axis since this is a 2.5D game. The Box has the Tag Moveable, so the Player script knows it can move it.
The Pressure Pad is a Box Collider set to be a Trigger and a child with a cube mesh on it for a visual pad that will change Color when the Box is on it.
In the Player script, we need to add a new variable.
- Push power is what the velocity will be multiplied by on the Box.
We use this method from the Character Controller to check if the Player is pushing against the Box. If the hit object is tagged as Moveable, we get the Rigidbody, and we then create a direction to push the Box by checking which direction on the x-axis the Player was moving when the hit occurred. Then to move the Box, we change the velocity on the Rigidbody to push direction multiplied by the push power of the Player.
The Player can now push the Box.
To get the Pressure Pad to detect the Box, we need a few variables.
- How close to the center the Box needs to be to activate the Pad.
- The Color of the Pad when activated.
- A bool to know if the Pad has been triggered.
- A reference to the child’s Mesh Renderer.
In Start, we get the reference to the child’s Mesh Renderer component.
We use OnTriggerStay to check each frame if the Pad is not triggered to see if the Box is close enough to the Pad center. If the Box is close enough, we set its Rigidbody to Kinematic so the Player can no longer move it, trigger the Pad and change it to the activated Color.
When the Box is within 0.1 of the Pad’s center, the Box becomes immobile, and the Pad changes Color.