This article will go over how to push an object.
A few things are needed when thinking about pushing an object.
- The object set to push.
- The player or object doing the pushing.
As above, the code is in the OnControllerColliderHit method. What the method does is when the PlayerController component is hit by a collider, it sends information. How you use that information is up to what is happening. In this case, we’re using it to push a block. The player runs into a cube that is tagged as a “Pushable” allowing for a way to be identified. The information of the block is stored in the hit variable, and if it’s tagged as a “Pushable” we try to grab the Rigidbody attached to it. If it has one at least. If it doesn’t or it is set to kinematic (which tells it not to allow forces to be applied to it), we don’t do anything. If the object is below us, we also don’t do anything. After all of that we make a new Vector3 variable for the move direction of the object which is just the direction that the player is moving in when it collided with the object. Then we set the velocity of the objects rigidbody to the move direction vector and a push power that was assigned.
Next is getting a pressure plate to trigger with the block on it.
This script is on the pressure plate object. When the block is pushed into the trigger, you check to see if it’s as far as you want. Checking to see if the position inside the trigger is where you’d like it to be for it to activate. Once it’s on the plate as far as needed, you can use that to activate something. A door, a bridge, etc. It’s a distance check between the plate and the object being pushed. You would then set the rigidbody of the object to kinematic for it to stop being moved when you push it.
With that it’s on to the next.