Pushing Objects in Unity to Complete Puzzles

Now that we have climbed in between the walls, there’s a box that the Player needs to push onto the yellow area.

If you have somehow searched for the CharacterColliderHit function in Unity, you might have encountered the Unity manual example regarding pushing an object. You can click here to reach it. The example provided simply points out the way for the character to push an object.

If you check the properties of ControllerColliderHit, you will realize a property of moveDirection exists:

moveDirection returns a Vector3 value, so that we will know that in which direction the player was moving before collision occured. As can be observed from the Unity example, we need to manipulate the Rigidbody component of the object that we are colliding with in order to create a sense of “pushing”. Also, we need to create a functionality to check if the object is actually on the Yellow zone.

So here’s my solution:

Do not forget to tag the object(s) you want to be moved (well, even if you forget you will realize it). So, I have tagged the box as “Movable” and checked the tag within the OnCharacterColliderHit method. I also did not want to be able to push it while on air. Then, I have tried to cache it’s rigidbody and null checked to prevent any errors within the game. Push force is a float variable with a value of 2. Here’s the result:

Since we do not want it to be rotate like that, we can simply freeze the Rotation on the Z axis to prevent this. Just to be safe, it might be better to freeze rotation on all axis — easy fix.

Now, we want the box to stick on the position provided with a Yellow Pad.

One solution might be to check the position of the box and the pad , and maybe provide an interval that will be acceptable for us.

The pad consists of a Display child object(the yellow pad) and a cube with box collider.

As we need a new behavior by the pressure pad, it is better to create a script for it.

To prevent the box from moving further, we need to either disable it’s rigidbody or set it to kinematic so that it will not be effected by the forces. To check if the box is actually on the desired position, we can measure the distance between the pad and the box.

Since we do not need this script after we move the box on the pad, we can destroy it at the end. Despite it is not very clear on the shot, the pad also turns green.

Unity Developer