- Home /
Question by
united4life · Apr 05, 2013 at 10:43 AM ·
input.mousepositionpositon
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.
Comment
Answer by Chronos-L · Apr 05, 2013 at 10:56 AM
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 co$$anonymous$$g back to 20... but it should not go beyond 20.
For it to never go to 20.06, you can try:
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);
//uJS
plane.transform.position.x = $$anonymous$$athf.Clamp( plane.transform.position.x, -20f, 20f );
//C#
Vector3 p = plane.transform.position;
plane.transform.position = new Vector3( $$anonymous$$athf.Clamp( p.x, -20f, 20f ), p.y, p.z );
}
yeah now its working.... thanks buddy.... clamp i didnt know