Hi all, it's my first post in Unity community forum I'm currently trying to make my ball moving by using gyroscope. I want to use almost the same movement logic as i used in PC movement. On PC it works well.However, on mobiles i can move my ball only up and down. I have no idea what is wrong in my code, please, help me. That's a piece of PlayerController script, that matters: Code (CSharp): void Update () { Rigidbody rigidbody = transform.GetComponent<Rigidbody>(); Vector3 direction = Vector3.zero; //PC code works great if (SystemInfo.deviceType == DeviceType.Desktop) { if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) { direction = -Vector3.left; } if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) { direction = Vector3.left; } if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) { direction = Vector3.forward; } if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) { direction = -Vector3.forward; } rigidbody.AddTorque(direction * speed); } //My ball moves only up and down, no left or right if (SystemInfo.deviceType == DeviceType.Handheld) { float x = Input.acceleration.x; float y = Input.acceleration.y; if (x > 0) { direction = -Vector3.forward; } if (x < 0) { direction = Vector3.forward; } if (y > 0) { direction = -Vector3.left; } if (y < 0) { direction = Vector3.left; } rigidbody.AddTorque(direction * speed); } }
Well, your Input.acceleration will probably always be a non zero value, but your logic overrides your input, because you are setting an absolute value for your direction. Set a threshold and allow vertical and horizontal input at teh same time: Code (CSharp): //My ball moves only up and down, no left or right if (SystemInfo.deviceType == DeviceType.Handheld) { float threshold = 0.2f; float x = Input.acceleration.x; float y = Input.acceleration.y; if (x > threshold) { direction -= Vector3.forward; } if (x < -threshold) { direction += Vector3.forward; } if (y > threshold) { direction -= Vector3.left; } if (y < -threshold) { direction += Vector3.left; } direction = direction.normalized; rigidbody.AddTorque(direction * speed); }
Johannski is correct about what he said. Your y input code is overwriting your x input code. That is why it was only going up and down. Just Debug.Log or display 'direction' values so you can analyse what is going on. Also, you should really be using an 'else' prior to every second 'if'. Learn to debug otherwise it will always be WTF?