limitation of motion the child object

Hi please help to finish this code, I need to limit the movement of the child object in the Z axis

crane boom

public class NewBehaviourScript : MonoBehaviour {

public float SpeedX = 0f;
public float SpeedY = 0f;
public float SpeedZ = 0f;

void Start ()
{

}


void Update ()
{
if (Input.GetKey (KeyCode.W))
        transform.Translate(SpeedX, SpeedY, SpeedZ);
   

    if (Input.GetKey(KeyCode.S))
        transform.Translate(-SpeedX, -SpeedY, -SpeedZ);

 
}

}

1 Answer

1

What do you want to do ? If you want to limit the speed, you must use a rigibody, else with a if statement it should work.

if (transform.position.x <= MaxZ || transform.position.x >= MinZ)
		{
			if (Input.GetKey(KeyCode.W))
				transform.Translate(SpeedX, SpeedY, SpeedZ);
			if (Input.GetKey(KeyCode.S))
				transform.Translate(-SpeedX, -SpeedY, -SpeedZ);

		}
		else if (transform.position.x > MaxZ
		{
			transform.position.x = MaxZ;
		}
		else if (transform.position.x < MinZ)
		{
			transform.position.x = MinZ;
		}