I have a plane that a ball rolls around on that I’m rotating using input accelerometer values from a tablet. How can I limit the rotation in the x and z axis?
This is my current code:
private Rigidbody rb;
void Start() {
rb = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
float getHorizontal = Input.acceleration.x;
float getVetrical = Input.acceleration.y;
transform.Rotate (getVetrical, 0, -getHorizontal);
}
Use a simple if statement:
private Rigidbody rb;
private float maxRotX = 45, maxRotZ = 45;
float getHorizontal = 0, getVetrical = 0;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (transform.eulerAngles.x < maxRotX && transform.eulerAngles.x > -maxRotX)
getHorizontal = Input.acceleration.x;
if (transform.eulerAngles.z < maxRotZ && transform.eulerAngles.z > -maxRotZ)
getVetrical = Input.acceleration.y;
transform.Rotate(getVetrical, 0, -getHorizontal);
}
If you are not going to exceed 90 degree and deal with singularity issues, following modifications might work for you:
void Update()
{
if (transform.eulerAngles.x < maxRotX && transform.eulerAngles.x > -maxRotX)
getHorizontal = Input.acceleration.x;
else
getHorizontal = 0f;
if (transform.eulerAngles.z < maxRotZ && transform.eulerAngles.z > -maxRotZ)
getVetrical = Input.acceleration.y;
else
getVetrical = 0f;
transform.Rotate(getVetrical, 0, -getHorizontal);
}