Skip to content

Instantly share code, notes, and snippets.

@petecleary
Created October 17, 2017 06:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petecleary/b63acc149b618c0d08041e06f5bf915c to your computer and use it in GitHub Desktop.
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
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