Created
October 17, 2017 06:36
-
-
Save petecleary/b63acc149b618c0d08041e06f5bf915c to your computer and use it in GitHub Desktop.
Unity mobile compass controller, how to enable and rotate the transform based on the magnetic heading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
using UnityEngine.UI; //required for Input.compass | |
public float compassSmooth = 0.5f; | |
private float m_lastMagneticHeading = 0f; | |
public class CompassController : MonoBehaviour { | |
// Use this for initialization | |
void Start () { | |
// If you need an accurate heading to true north, | |
// start the location service so Unity can correct for local deviations: | |
Input.location.Start(); | |
// Start the compass. | |
Input.compass.enabled = true; | |
} | |
// Update is called once per frame | |
private void Update() | |
{ | |
//do rotation based on compass | |
float currentMagneticHeading = (float)Math.Round(Input.compass.magneticHeading, 2); | |
if (m_lastMagneticHeading < currentMagneticHeading - compassSmooth || m_lastMagneticHeading > currentMagneticHeading + compassSmooth) | |
{ | |
m_lastMagneticHeading = currentMagneticHeading; | |
transform.localRotation = Quaternion.Euler(0, m_lastMagneticHeading, 0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment