Day 95: Pushing Objects in Unity to Complete Puzzles

Tyler Smallwood
4 min readNov 24, 2021

--

Objective: Push cube on to pressure plate and turn it blue.

For this we will need a cube that has a tag called “Moving Box”. It will need a rigidbody and a Box Collider. We do not wish to have the box rotate while being pushed so we will use the Constraints on all x, y, and z so it will now rotate.

Next will be the pressure pad. For this we will create a cube and delete the Mesh render.

We will need another cube as a Child to the Pressure_Pad. This one will have only the Mesh_Render and it’s own material.

After creating the second cube and setting it as a child to the Pressure Pad. We will move back to the Pressure Pad and set the scale down to .1 on the y. In the Box Collider, we will size it up on the Y to 10.

Now we need to add to the Player script to push the cube. In the Player script in the OnControllerColliderHit() method we will check to see if we are touching the moveable box.

Next we will do a quick check and see if the Box has a rigidbody and if it does not have one, give a message in the console.

If it does we will check to see where we are contacting the box at. If the hit.moveDirection point is less than -3 on the Y asix, we will return and not move the box. If it is higher than that we will push the box.

Before we move on in the OnCharacterColliderHit() method, we need to know how strong to push the box. At the top we will need a SerializeField float named _pushPower.

To push we will create a local Vector3 variable and assign a new Vector3 and add in the hit.moveDirection on the X axis. All that is left to push the box is to set the Boxes velocity to equal the local variable pushDir multiplied by the _pushPower. This is move the box.

Now we need to create a Pressure Plate script. This script will change colors when there is something on it and cause the object to stop moving. In this script the first thing we will do is to have a reference to the Renderer of the display box.

Next we need to use OnTriggerStay method. This will allow the box to get on a good portion of the pressure pad before it turns colors. In this method we will check to see if it is the Moving Box that has entered the trigger field. If it is we will then check the distance the box is compared to the pressure pad. Once it gets to about .3f away from the pad we will set the Rigidbody of the box to isKinematic = true. This will stop the box. Next is to set the color of the display to blue.

All that is left is to assign the display to the variable on the pressure pad.

Now we have a working Pressure Pad and moveable boxes!!

Thank you for reading and have a wonderful day!

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet