Unity Development — Pushing Blocks

Christopher Graf
4 min readJul 29, 2021

From The Adventures of Lolo to The Legend of Zelda, pushing blocks to solve puzzles is another video game classic. How about we implement one version for ourselves.

In this example, we are going to use a Player that is controlled with a Character Controller component. This component will automatically provide a collider and a method we can use to our advantage.

We will also need a cube with a Box Collider and a Rigidbody. Make sure the rotation on the Rigidbody is constrained as it will help us out when pushing. Also add a tag to the box that we can check for in code. Something like “MovableBox.”

Last, we need a pressure pad, or some area that the box is supposed to go to complete the puzzle. This can have a visual look, but also needs a trigger Box Collider so that we can push into it.

Once that is all setup, we can go into the Player script. The Character Controller gives us a useful function called ‘OnControllerColliderHit().’ Just as it sounds, it is called when the collider is hit by another collider with a Rigidbody. To make this work to our advantage, first we need to check the tag and make sure it is the cube we want to push. We should also check if we are grounded when pushing.

Since confirming it is the box we are hitting, we can get to work. When moving the object, we need to use its Rigidbody to move. Get a reference to that Rigidbody and then check to see if it is null. Also check if it is Kinematic. In Unity this means that it can only be moved in code and not through any form of physics.

With the reference to the Rigidbody, you can then make a new Vector3 relating to the direction of the collision. Use this with some force (the Player speed or another variable determining push power) to manipulate the box’s velocity and you have movement.

Time for the pressure pad to react to the block. Make a script for the pressure pad. Since we want the box to act as if it is ‘fully’ on the pad as opposed to just triggering it, we are going to use OnTriggerStay() as opposed to OnTriggerEnter(). We will still be checking for the correct tag as usual, but we are also going to be checking for an X range to see that it is really covering the pad. In my case, the pad’s X position is 0.2, so we are going to check within a small range around there.

From there, you can do almost anything you desire. You could have this go to a cutscene, open a door, release some enemies, destroy some enemies. It is all up to you. In my case, I turn the box Kinematic so that it cannot be moved from that position. I also get a reference to the visual display of the pad and change the color to signify a change or activation and finally destroy the script itself, so that it does not call OnTriggerStay() infinitely. The code looks something like this.

How creative can you get with your box pushing puzzles?

--

--