Moving objects by pushing in Unity

Daniel Kirwan
3 min readAug 2, 2021

--

Objective: Move an object with the player in Unity

Pushing objects can be great little puzzles for the player to investigate. In this article I am going to move a cube with the player.

First, make sure that the cube has a rigidbody component. If you’ve been following the previous articles about the character controller then this will be pretty straight forward, for those of you coming in new I’ll take it slow.

I made a global variable that I can adjust in the editor and that is called push power.

I have made this 3f in the editor.

The method I’m using is similar to the oncolldierenter method for box/circle colliders in Unity but is specifically for detecting collisions with a character controller component.

First I am checking to make sure that the object I’m colliding with is a moveable box, you can change this to the tag that you have for you object.

Then I am assigning the rigidbody variable to the rigidbody that is attached to the collided object. The next thing to do is to null check this, so that if there is no rigidbody then the method simply returns and doesn’t run any further code. I do a similar check to make sure that the object is not below the player.

I then assign the move direction of the player to a vector and use this as the direction that I want the object to move.

Now let’s go back into Unity and try it out. You will probably get some movement like the following:

This is not the box movement that I desire but don’t worry it is an easy and simple fix. Find the box in question in the hierarchy and look at the rigidbody component. Look for the constraints attributes:

If you tick the boxes that I have highlighted this will make it so that the box cannot rotate in any direction but can still be pushed. Making this change will result in the box being pushed like so:

And that is it for this article, I hope you found it useful.

--

--

Daniel Kirwan
Daniel Kirwan

No responses yet