[Solved] Accelerometer calibration on iOS not working

Hi,

I am using the accelerometer in my mobile game. I want the player to hold the phone straight and not flat (like on a table) and calibrate the accelerometer on scene start like this:

private void Start()
{
    Calibrate();
}

public void Calibrate()
{
    Vector3 accelerationSnapshot = Input.acceleration;

    Quaternion rotateQuaternion = Quaternion.FromToRotation(
        new Vector3(0.0f, 0.0f, -1.0f), accelerationSnapshot);

    calibrationQuaternion = Quaternion.Inverse(rotateQuaternion);
}

void Update()
{
    Vector3 theAcceleration = Input.acceleration;
    Vector3 fixedAcceleration = calibrationQuaternion * theAcceleration;

    movement = new Vector3(fixedAcceleration.x*movementSpeed, fixedAcceleration.y*movementSpeed, 0);
}

private void FixedUpdate()
{
        rb2D.velocity = movement;
}

This works perfect on Android but building the iOS version, my gameObject just falls down and I have to tilt the phone flat.

Any idea why this is not working?

Specs:
Unity 2018.4.0f1
iOS 12.3 (iPhone 6s)
Xcode 10.2.1
Accelerometer frequency is 60hz
target minimum iOS is 9.0 in Unity

I found out, that the first call to Input.acceleration; returns Vector3.zero. Even though I am holding my phone up. I will try to create a small delay. Maybe this will help.

EDIT: Okaaaay… iPhone just needs some more time. I made my script wait for 1 second and then calibrate it. Now it’s working.

1 Like

Does it work when you build it to your iPhone?

Without waiting a second, it does not work correctly on the iPhone build (6S). But since I am fading the scene for 2 seconds it’s okay.

1 Like