Using physics — Pushing objects in Unity

Luke Duckett
Games Development Journal
3 min readJul 23, 2021

--

In the scene, I have a pressure plate set and a box set up. I will go over the logic on how to both push the box and respond to it when it arrives on the pressure plate. I already have a character created, which I created here.

The box we are pushing needs a rigid body and a collider attached. The collider will not be a trigger and the rigid body will use gravity and be frozen on the x, y and z angles.

The pressure pad has 2 parts. The parent object with a box collider (trigger) and the child which has a mesh renderer. When the cube is pushed onto the pressure pad we will change the pressure pads colour to green and stop the cube from moving.

On the player script we need to check for a collision in our on controller collider hit function. I have added a new tag called “PushableObject” which I have added to the cube. We need to check for and apply force to the rigid boy of the box. We assign a vector 3 as a new variable called push direction. This will be the direction from where we hit the collider of the box. We can now apply the push direction with a new float variable (_pushStrength) to the velocity of our box.

We can now work on our pressure plate. Create a new script and attach it to the parent object in the pressure pad. On this script we are going to check the distance between the center of the box and pressure plate while the box is in within the pressure pads collider. We do this using Vector 3.Distance.

We then check if the distance is within a small margin of error ( I provided 0.05f as the margin of error, without this margin it can be very difficult to get the box on the plate).

Once the box is in the right spot we need to access to the rigid body and make it kinematic so it will no longer move

Next we access the material in our mesh renderer and change the colour to green.

Finally we remove the script using Destroy(this).

Now we can test our functionality.

That’s all for now.

--

--

Luke Duckett
Games Development Journal

🎮 First Nations Unity Dev from Wonnarua country 🏞️ | From Player to Lifelong Learner: Crafting Games, Debugging Code, and Embracing New Technology