Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

[Solved] Accelerometer calibration on iOS not working

Discussion in 'iOS and tvOS' started by Irrgeist, May 24, 2019.

  1. Irrgeist

    Irrgeist

    Joined:
    Jul 9, 2015
    Posts:
    28
    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:
    Code (CSharp):
    1. private void Start()
    2. {
    3.     Calibrate();
    4. }
    5.  
    6. public void Calibrate()
    7. {
    8.     Vector3 accelerationSnapshot = Input.acceleration;
    9.  
    10.     Quaternion rotateQuaternion = Quaternion.FromToRotation(
    11.         new Vector3(0.0f, 0.0f, -1.0f), accelerationSnapshot);
    12.  
    13.     calibrationQuaternion = Quaternion.Inverse(rotateQuaternion);
    14. }
    15.  
    16. void Update()
    17. {
    18.     Vector3 theAcceleration = Input.acceleration;
    19.     Vector3 fixedAcceleration = calibrationQuaternion * theAcceleration;
    20.  
    21.     movement = new Vector3(fixedAcceleration.x*movementSpeed, fixedAcceleration.y*movementSpeed, 0);
    22. }
    23.  
    24. private void FixedUpdate()
    25. {
    26.         rb2D.velocity = movement;
    27. }
    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
     
    Last edited: May 24, 2019
  2. Irrgeist

    Irrgeist

    Joined:
    Jul 9, 2015
    Posts:
    28
    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.
     
    Last edited: May 24, 2019
    Essexrookie likes this.
  3. Essexrookie

    Essexrookie

    Joined:
    Apr 29, 2019
    Posts:
    2
    Does it work when you build it to your iPhone?
     
  4. Irrgeist

    Irrgeist

    Joined:
    Jul 9, 2015
    Posts:
    28
    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.
     
    Essexrookie likes this.