2.5D Platformer: Pushing a box

The box is in the way, so I must push it to the pressure pad!

The cool thing about having to push a box in a direction is that I can also use the OnControllerColliderHit()I have in the player class as I did on the previous medium post. Except, instead of using hit.point and hit.normal, I want to use hit.moveDirection to move the box upon colliding with it.

The move direction property in hit takes the direction of the character controller when the collision occurred.

In the OnControllerColliderHit(), I added:

if(hit.transform.CompareTag(“Moving Box”))
Rigidbody rigidbody = hit.transform.GetComponent<Rigidbody>();
if(rigidbody != null)
Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, 0);
rigidbody.velocity = pushDir * pushPower;

If I (The player) hit the box that can move, I want to grab the reference of the box’s RigidBody component. If rigidbody is not null, I want to store the x-direction of the moving box in a Vector3. Lastly, I want to grab the velocity of the rigidbody and assign the new Vector3 * the push power. This will allow us to push the moving box only on the x-axis.

Now I want the pressure pad to detect the box and change the material color. So I created a new script and attached it to the yellow pressure pad game object.

Since I want the pressure pad to detect the box, I will use the OnTriggerStay() and calculate the distance between the box and the pressure pad.

private void OnTriggerStay(Collider other)
if(other.CompareTag(“Moving Box”))
float distance = Vector3.Distance(transform.position, other.transform.position);
Debug.Log(“Distance: “ + distance);
if(distance < 0.1f)
Rigidbody _rb = other.GetComponent<Rigidbody>();
if(_rb != null)
_rb.isKinematic = true;
if(_rend != null)
_rend.material.color = _activationColor;

If the moving box is detected by using a tag, I want to calculate the distance between the pressure pad, and the box. If the distance is less than 0.1f, we have successfully moved the box on the pressure pad. I also want to store the rigidbody component from the box and set isKinematic to true. It will disable the force applied to the rigidbody. I also stored reference to the pressure pads MeshRenderer component for access to the material. It will allow me to change the color of the pressure pad when successful.

Now that I have a working pressure pad and a moving box, I can create different puzzles that can trigger different things when the box activates the pad.




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store