In this article, we are going to cover how to create a pressure pad that could be used to trigger other objects in your platformer.
We are going to want to detect when the desired object has been placed on the pressure pad, so we are going to add a Box Collider, set Is Trigger to true, and move the center position to 1. This will place the Box Collider above the pressure pad game object.
We will create a script for the pressure pad and use the OnTriggerStay method to detect when the object is staying in the box collider on the pressure pad. Now, making sure the desired object being place on the pressure pad is the one you want, you can check the tag of the other object. In this example, we are checking to see if it is the moving box.
The object to be placed on the pressure pad usually needs to have a certain amount of it covering the pressure pad to activate it. We are going to need to know the distance between the pressure pad and the box being placed on the pad. Using Vector3.Distance, we can measure the distance of two positions and we can store this in a variable. If the distance between these two objects positions’ are less than a certain the determined amount than we can trigger whatever we want.
The one thing we are going to do is stop the box from being pushed any further. We need to get access to the box’s Rigidbody by using the other variable. Once the Rigidbody is cached we can set kinematic true, which doesn’t allow any forces to act on the box. One thing to note is to Null Check when you want to get components of game objects to avoid errors.
The last thing is to destroy the script, so it doesn’t continue to run once the box gets into position. We do this by using Destroy(this).
This pressure pad is a staple for puzzles and gives the level designer another tool.