Creating A Pressure Plate in Unity!
Objective: Create a pressure plate that reacts when an object is push on top.
In the last tutorial I showed you how to push an object. Today’s tutorial I am going to show you how to set up a pressure plate and have it react to having an object pushed on top of it.
To begin, I have a short yellow cube on my path beyond the pushing object. I want to have to push this object almost all the way on top of the pressure plate before the pressure plate reacts. When the object is almost all the way on top of the pressure plate I want the object to be stuck on top of the pressure plate and the pressure plate to turn blue.
Since we need the pressure plate to be checking for the box we need to create a script for the pressure plate. In the script we need to check for if the box stays inside the pressure plates collider using the tag we created in the last tutorial.
Now, how do we check if the box is most of the way on top of the pressure plate? We use Vector3 Distance. If the distance equals 0 then the objects is directly in the center. Use the Debug Log to measure the distance.
Now when the box collides with the pressure plate the distance will be displayed in the controls view. Start your game and push the box slowly to where you want the reaction to be a note the distance displayed.
Using the distance you are comfortable with we can now set the next the next parameter. If the distance is equal to or less than, for me it’s 0.05, then we want to have our reaction.
One way we can make the moving box immobile is to use “is.Kinematic” Turning this true means forces, collisions, or joints will no longer affect the rigidbody. The rigidbody will now be under control of animation or script control. So we need to grab the rigidbody from the moving box, as well as null check. It is always important to perform a null check after using get component.
If you run your game now you will notice the box becoming immobile once it reaches the distance limit.
Let’s finish this lesson off with a color change to visually signify that the pressure plate has been activated. To do this we need to grab the mesh renderer component. Now, for me my display is child under the pressure play so I need to use the get components in children.
Both of these get components are being continuously called while the box is stuck on the pressure plat. So, to end the calls we can simply destroy it once it has been called once.
Now you have a functioning pressure plate that can be used in your game for what ever you see fit. Drop a draw bridge, activate another part of your level, or even finish the level. You can easily attach those to your pressure plate. As always, don’t be afraid to experiment with your code, and I’ll see you in the next tutorial!