Limiting the position of a gameobjevt between two values

I am moving my plane. But it should only move between two positions like -20f to 20f.

I am using this logic

if(plane.transform.position.x >= -20f && plane.transform.position.x <= 20f)
		{
			if(Input.mousePosition.x< 0)
				plane.transform.Translate(-Vector3.right * speed * 2 * Time.deltaTime);
			
			else if(Input.mousePosition.x > 0)
				plane.transform.Translate(Vector3.right * speed * 2 * Time.deltaTime);
		}

The problem is it is going beyound 20f… i.e. it goes to 20.06… and then it stops because now it willl not enter inside this condition.

1 Answer

1

Have you tried Mathf.Clamp?

if(plane.transform.position.x >= -20f && plane.transform.position.x <= 20f)
{
    ...
}
else { //out of range

    //uJS
    plane.transform.position.x = Mathf.Clamp( plane.transform.position.x, -20f, 20f );

   //C#
   Vector3 p = plane.transform.position;
   plane.transform.position = new Vector3( Mathf.Clamp( p.x, -20f, 20f ), p.y, p.z );;
}

still it is going to 20.06... but with this method at least it is coming back to 20... but it should not go beyond 20.

yeah now its working.... thanks buddy.... clamp i didnt know