Maximum translation?

Hello,

I’m using the following script to move my object side to side:

var speed = 10.0;

function Update () {
	var translation = Input.GetAxis ("Horizontal") * speed;
	translation *= Time.deltaTime;
	transform.Translate (translation, 0, 0);
}

Is there a way I can restrict the translation to say only go between -2 and 2 before stopping?

Thanks,
Stuart

Try this:

var speed = 10.0;

function Update () {
   var translation = Input.GetAxis ("Horizontal") * speed;
   translation *= Time.deltaTime;
   transform.Translate ( Mathf.Clamp(translation,-2f,2f), 0, 0);
}

Thanks for the reply but Im just getting this error:

245334--8824--$picture_1_547.png

This is from the scripting reference of Mathf.Clamp
:

// Set the position of the transform to be that of the time
// but never less than 1 or more than 3
function Update ()
{
    transform.position.x = Mathf.Clamp(Time.time, 1.0, 3.0);
}

I dont know if your error is the result of c# syntax (2.f), or if you can do that in js also. Hope it helps :slight_smile:

Im using Javascript but using that method it just moves on it’s own, ignoring my input?

stuthemoo - that’s actually a pretty clear error message, it’s saying it doesn’t like the f (so changing 2f to 2.0 will make it work)

Admittedly the script doesn’t do what you’re after anyway because it clamps the speed, not the position. Try this one :

var speed = 10.0; 

function Update () { 
   var translation = Input.GetAxis ("Horizontal") * speed; 
   translation *= Time.deltaTime; 
   transform.position.x = Mathf.Clamp(transform.position.x + translation, -2.0, 2.0); 
}

Thanks Sycle, that worked. Except the movement is now really jumpy and not smooth like it was before?

Weird :frowning: I tested both ways and the movement looked identical to me… maybe Translate is doing something different under the hood

you could try changing the script to :

var speed = 10.0; 

function Update () { 
   var translation = Input.GetAxis ("Horizontal") * speed; 
   translation *= Time.deltaTime; 
   transform.Translate (translation, 0, 0); 
   
   if (transform.position.x < -2.0)
		transform.position.x = -2.0;
		
   if (transform.position.x > 2.0)
		transform.position.x = 2.0;
}

it uses Translate as before and just checks if it’s gone past the extremes and sets it back. Kind of clunky, but it might sidestep the jumpiness issue.

Hmm… Today your first script isn’t jumpy at all :sweat_smile: maybe it was just the lag of my computer having a lot of applications open at the same time.

Thanks a lot,
Stuart :smile: