Creating Pushable Objects
Using Character Controller to push Rigidbody objects
Creating wall jump was the first step to adding more features to our 2.5D platform game. Now it is time to add pushable objects!
As you would have known, since we have created our playable character within a Character Controller, we are unable to interact with Rigidbody objects normally, this feature needs to be scripted into our code to become accessible.
First create an pushable object in the scene, it can be anything, but in my scenario I created a 3D cube. This cube is going to hold both a Box Collider and also Rigidbody. I am also going to create a new tag called “Pushables” which will determine all objects under this tag will be an interactive object.
In our player script, we are going to continue using the collision hit method which controls impact point forces. Similar to how we were checking for collision for walls, we need to first check if our player is colliding with any “Pushable” objects.
Create an If statement to check if the hit collider tag has “Pushable” then we need to check if that collided object has an Rigidbody.
As best practices it is always best to null check whenever we try reference another game object. In this null check, we need to add in the direction that the box can move in. In this case we only want the box to move in the x axis, therefore we zero out on the Y and Z axis.
Then we need to calculate the push force of the cube, this can easily be done by using the player’s velocity. Therefore the box’s velocity = the push direction multiplied by the push force. The push force is going to be an global variable which we need to define.
Back in Unity, we can see that the box with the rigidbody is now able to be push by our player in any X axis.