Restricting an object on its Zaxis.

Hello everyone i would like to modify Unitys PlatformerPushBodies script so that an object can not be pushed on its Z-axis.

This is Unitys Script and i want to change it so when i push the object it only goes left/right and up/down. Not turn and go off the sides because im working on a 2.5d Side Scroller. Thank You

// Script added to a player for it to be able to push rigidbodies around.

// How hard the player can push
var pushPower = 0.5;

// Which layers the player can push
// This is useful to make unpushable rigidbodies
var pushLayers : LayerMask = -1;

// pointer to the player so we can get values from it quickly
private var controller : PlatformerController;

function Start () {
    controller = GetComponent (PlatformerController);
}

function OnControllerColliderHit (hit : ControllerColliderHit) {
    var body : Rigidbody = hit.collider.attachedRigidbody;
    // no rigidbody
    if (body == null || body.isKinematic)
        return;

    // Only push rigidbodies in the right layers
    var bodyLayerMask = 1 << body.gameObject.layer;
    if ((bodyLayerMask & pushLayers.value) == 0)
        return;

    // We dont want to push objects below us
    if (hit.moveDirection.y < -0.3) 
        return;

    // Calculate push direction from move direction, we only push objects to the sides
    // never up and down
    var pushDir = Vector3 (hit.moveDirection.x, 0, 0);

    // push with move speed but never more than walkspeed
    body.velocity = pushDir * pushPower * Mathf.Min (controller.GetSpeed (), controller.movement.walkSpeed);
}

Thank You ps. I am very new to scripting, ive been trying to script for only 2 weeks so this was sort of a complicated script for me.

it's quite a dirty way of doing it, but this is the way i'd do it: you declare a variable:

var depth = 0.0;

to the editor, (put it outside any functions, right up at the top of the script)

then add:

body.position.z = depth;

right at the bottom of the script (but still inside the OnControllerColliderHit function)

then you can change the variable "depth" in the editor, and your object will stay at that Z co-ordinate

seeing as you're new to scripting i'm happy to explain it differently if you want; and if someone else has a better way of doing it, do tell.

hope that helped.

Check the Z axis on Freeze Position for the rigidbody constraints.