Pushing Objects in Unity to Complete Puzzles

Samarth Dhroov
3 min readJan 3, 2022

The exercise here demonstrates pushing an object in Unity using rigid body.

The project has a requirement to get an object fixated on another object to have a puzzle solved. So, there are three game object interacting here.

Unity

There are two parts to this solution.

First, the player must be able to push the object. Second, the object must get locked on the destination.

  1. Pushing the object

In the in built class above, there is a property which can be used here.

moveDirection

Basically, this property keeps track of the direction the controller is moving at all times.

So, once that data is available, the velocity property of the rigid body component can be altered on the box object.

Please refer the link above which shortly solves this task.

  • Add the following code in the player script.
C#

Note: pushPower is a private variable with a float value.

2. Locking the object

This is the target position where the box shall be fixated. It can be seen that there are two object here. The big box without mesh is the pad and the yellow cube is the display.

The task is to bring the box on this display just enough so that it looks like the box got locked onto it.

For that, a simple distance method from the vector class can be used.

  • Add a script to the pad object.
  • Add an OnTriggerStay( ) method to check the collision.
  • Get a reference to the rigid body of the box object and the Mesh Renderer of the display object. (This step would allow to change the color of the display to make it obvious that the box got fixed.)
  • Destroy the pad object so that the process gets finished without looping.
C#

That should be it :)

Here is the final result.

Thank you very much

--

--