Help! I can't get this code to function correctly
I'm quite new to Unity and am trying to make a simple ball maze game where you rotate the maze to make the ball roll around. I have made code to rotate the maze and lock it from rotating too much, which works with the W and D keys, but with the A and S keys the maze rotates without locking. If anyone can figure out why this is happening it would be greatly appreciated!
void Update ()
{
if (Input.GetKey (KeyCode.W))
{
if (transform.eulerAngles.z < 20)
{
transform.Rotate (Vector3.forward * Input.GetAxis ("Vertical"));
}
}
if (Input.GetKey (KeyCode.A))
{
if (transform.eulerAngles.x > -20)
{
transform.Rotate (Vector3.right * Input.GetAxis ("Horizontal"));
}
}
if (Input.GetKey (KeyCode.S))
{
if (transform.eulerAngles.z > -20)
{
transform.Rotate (Vector3.forward * Input.GetAxis ("Vertical"));
}
}
if (Input.GetKey (KeyCode.D))
{
if (transform.eulerAngles.x < 20)
{
transform.Rotate (Vector3.right * Input.GetAxis ("Horizontal"));
}
}
}
Answer by DizzyWascal · Mar 09, 2018 at 12:20 AM
I tried to get those if statements to work but I gave up trying to get that code to work, because locking the object rotation wasn't really working will with if statements.
Try this code, I hope I got the functionality you were trying to go for:
private float xRotate = 0f;
private float zRotate = 0f;
void Update()
{
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
{
xRotate = Mathf.Clamp(xRotate + Input.GetAxis("Horizontal"), -20f, 20f);
transform.eulerAngles = new Vector3(xRotate,
transform.eulerAngles.y, transform.eulerAngles.z);
}
if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S))
{
zRotate = Mathf.Clamp(zRotate + Input.GetAxis("Vertical"), -20f, 20f);
transform.eulerAngles = new Vector3(transform.eulerAngles.x,
transform.eulerAngles.y, zRotate);
}
}
Wow! Thanks so much, this has been a huge help, I was trying to get $$anonymous$$athf.Clamp to work, but I couldn't figure out how to do so, that's really smart!