2
\$\begingroup\$

I'm making a game where you control a platform with balls falling on it, and you have to balance the balls and prevent them from falling off. I'm currently using a mouse to control it with this code:

transform.rotation.eulerAngles.z += Input.GetAxisRaw("Mouse X");
transform.rotation.eulerAngles.x += Input.GetAxisRaw("Mouse Y");

I'm trying to make this an Android app, and want to use motion controls so I can tilt the device, as if it were the platform. I figured I would use the accelerometer for this.

Any ideas on how to do this in Unity?

\$\endgroup\$
  • 1
    \$\begingroup\$ Unity wraps the accelerometer. Plenty of links and examples \$\endgroup\$ – Sergio Jul 15 '14 at 22:26
  • \$\begingroup\$ Pedantically speaking, rotation of a device is detected using a gyroscope, not an accelerometer (though they are often combined into a single chip). The former senses angular acceleration, while the latter detects linear acceleration. \$\endgroup\$ – bcrist Jul 16 '14 at 2:33
  • \$\begingroup\$ @Sergio I've tried to use the documentation, but it hasn't worked for me. Can you give some sample code? \$\endgroup\$ – Chris Jul 16 '14 at 19:26
  • \$\begingroup\$ @bcrist Most devices don't have a gyro, apparently. My Galaxy S3 apparently does, and some code I wrote with the gyro didn't work. Can you give some code? \$\endgroup\$ – Chris Jul 16 '14 at 19:27
  • \$\begingroup\$ @Chris I've never done any mobile development with Unity; my experience with accel/gyros comes from embedded (microcontroller) programming. If you don't have a gyro, it can be faked by low-pass filtering the accelerometer output, on the assumption that most of the time, gravity is the only significant force detected. Even with a gyro, you usually want to combine it with this technique - the gyro is more accurate, but it only detects relative rotation, so it will drift without some absolute reference. \$\endgroup\$ – bcrist Jul 16 '14 at 19:59
0
\$\begingroup\$
public class AccelerometerRotation : MonoBehaviour
{
    [SerializeField] private float _speed = 5f;

    private void Update()
    {
        Vector3 accRotation = new Vector3 (Input.acceleration.x, 0.0f, Input.acceleration.y);
        this.transform.Rotate(accRotation * this._speed * Time.deltaTime);
    }
}

Input.acceleration

Transform.Rotate

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.