On Puzzles — Pressure Plates and Movable Boxes
Whether it is 2D or 3D, many games feature simple puzzles that the player must conquer in order to progress their story. Pressure plate systems are a staple of creating puzzles; you can use them to trigger a door opening, an enemy spawning, or a timer to allow passage through a previously blocked path.
The logic behind this system is quite simple:
First off, I tag the box I want to move (“MovingBox”) so I can access it during a collision by said tag.
The movable box will need a collider (box) and a rigidbody component. To stop the box from flipping, lock the rotations on the rigidbody now.
Moving onto the pressure plate we need another collider and a new C# script (PressurePad.cs).
Moving into the Player.cs (see previous articles), we need to add logic to apply force to the rigidbody located on the movable box. We can do this in OnControllerColliderHit, much like the wall jumping!
First, we will need a float value to track how much force we apply (pushPower)
With this block of code, we get access to the box’s rigidbody, then apply force to the moveDirection Vector3. This means we can push it left or right, in our case.
Moving onto the PressurePad.cs, we only need the OnTriggerStay function.
Here, we check to make sure that the box is mostly on top of the pressure plate (0.05f difference in centers). If it is, we lock the movable box by making it kinematic. We turn the color of the pressure plate blue, and then destroy this script so keep it from running in the background infinitely.
And that’s it! Using this simple system, you can create tons of puzzles and challenges for your player(s)!