player movement left/right limit along x

I’m using the following code for player movement. It’s a simple rail shooter type of movement. Think starfox movement with fixed forward speed, without any movement in the y.

The only problem is how to limit max movement left and right. I set up box colliders to limit movement left and right, but the player object (with this script) and a character controller componenet goes right through the walls set on the left and right… though the player collides with righidbody objects as desired pushing them out of the way-- utilizing box colliders as triggers etc…

var speed = 5.0; 
var forwardSpeed = .1;

function Update () {

var x = Input.GetAxis("Horizontal")*Time.deltaTime * speed;

transform.Translate (x, 0,0);

var translation = Time.deltaTime * forwardSpeed;
transform.Translate ( 0,0,translation);
}

var power = 4.0;

function OnControllerColliderHit (hit : ControllerColliderHit)
{
    var body : Rigidbody = hit.collider.attachedRigidbody;

    if (body == null || body.isKinematic)
    return;
    var pushDir = Vector3 (hit.moveDirection.x, 0, hit.moveDirection.z);
    body.velocity = pushDir * power;
}

how about defining the limits per hardcoding?
maybe:

var leftBorder : float = 0.0;
var rightBorder : float = 20.0;

function Update () {

  var x = Input.GetAxis("Horizontal")*Time.deltaTime * speed;
  
  transform.Translate (x, 0,0);
  
  //------NEW PART-----------
  if( transform.position.x < leftBorder )
    transform.position.x = leftBorder;
  if( transform.position.x > rightBorder )
    transform.position.x = rightBorder;
  //---------------------------

  var translation = Time.deltaTime * forwardSpeed;
  transform.Translate ( 0,0,translation);
} [/quote]

Mathf.Clamp is your friend :smile:

http://forum.unity3d.com/viewtopic.php?t=64316

Thank you.

It works using abeing’s code.
Thank you, giyomu. I have now read up on that and will try that next time. (I’m an artist learning to code.)