Limit transform.position.x

Hello all,

I’m trying to write code to constrain how far my object can move within a given area. I’m not getting a compiler error but my object also doesn’t stop at the boundary.

void Update () 
        var transV = Input.GetAxis("Vertical") * playerSpeedV * Time.deltaTime;
        var transH = Input.GetAxis("Horizontal") * playerSpeedH * Time.deltaTime;

        transform.Translate(transH, transV, 0);
        //Player position is equal to 'X' number equals 'X'.
        var playerPosition = transform.position;

        if (playerPosition.x >= 6)
            playerPosition.x = 6;
        if (playerPosition.x < -6)
            playerPosition.x = -6;


At no point in the code you posted do you set transform.position back to the value playerPosition. You are clamping the playerPosition variable successfully but right now that variable is going unused.

Also, you should not declare variables inside Update, nor call on transform, for performance reasons.
You don’t even need as many variables as you have. I’d simplify it to something like this:

var myT : Transform;
var playerSpeed : Vector2;

function Awake () {
myT = transform;

function Update () {
myT.translate (Input.GetAxis("Vertical") * playerSpeed.y * Time.deltaTime, Input.GetAxis("Horizontal") * playerSpeed.x * Time.deltaTime, 0);
myT.position.x = Mathf.Clamp (myT.position.x, -6, 6);