Pushing Objects in Unity
Objective: Enable Player to push objects to complete the level
We start by adding a tag of moveable to the box we want to move in the scene. next we check for the box inside the OnControllerColliderHit method using an if tag statement. Next we check that the moveable object has a Rigidbody attached by assigning it using GetComponent and running a null check to avoid errors.
We will create a private float for the pushing power and then move back to the ConControllerColliderHit method. After we have null checked the Rigidbody of the moveable object we create a Vector3 for push direction and assign it as a new Vector3 oh hit.moveDirection for the x and set y and z to 0. We then set the Rigidbody velocity of the object to the push direction by the push power.
As you can see above the box does move but we are getting a rolling of box and we want it to slide. This is an easy fix, we just freeze the rotation on the box on all 3 axis.
To get the pressure bad to work with the box been pushed on to it we create a script for the pressure bad and attach it. Inside the script we create an OnTriggerStay method and check if the tag is the moveable box(Moveable).
We then check to see if the distance between the center of the pad and the box are within range. If it is then we set the boxes Rigidbody to Kinematic making it stop and changing the pad color to green using the GetComponentInChildren to get the Meshrenderer. We null check both to prevent errors then destroy the script from the object when done.