Pushing Objects in Unity to Complete Puzzles
Another popular puzzle mechanic is pushing objects onto a pressure pad or towards a higher ledge to climb onto. Again, the character controller comes to the rescue, and Unity's own page on the ControllerCollider holds the answer for us!
The relevant code we’re interested is:
void OnControllerColliderHit(ControllerColliderHit hit)
Rigidbody body = hit.collider.attachedRigidbody; // Calculate push direction from move direction,
// we only push objects to the sides never up and down
Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z); // If you know how fast your character is trying to move,
// then you can also multiply the push velocity by that.
// Apply the push
body.velocity = pushDir * pushPower;
Unity basically wrote the code for us! Thanks Unity! Let’s prepare our box by tagging it as ‘MovingBox’.
Next, to comply with Unitys code, we’ll need a variable for pushing power so let’s create a global variable.
Now in our OnControllerColliderHit function, we’ll check for the box:
Now we’ll begin transferring our code. We’ll check for the rigidbody:
We’ll transfer the rest of the code but put it in in a null check.
Note we only used moveDirection.x. We’re only concerned with horizontal movement, so that’s the only axis we’ll be using in comparison to the original example. Everything else is exactly the same!
Now let’s see it in action!
It works, but oops…we don’t want the box rolling! That’s easily fixed by ticking off the rotational constraints of the boxes rigidbody.
Now let’s try it again!
Perfect! Tomorrow we’ll deal with the pressure pad!