Skip to content

Instantly share code, notes, and snippets.

@RyanWilson7
Last active November 26, 2020 06:48
Show Gist options
  • Save RyanWilson7/0cd368fc52d5b776903287428d7af2a4 to your computer and use it in GitHub Desktop.
Save RyanWilson7/0cd368fc52d5b776903287428d7af2a4 to your computer and use it in GitHub Desktop.
Unity script for rotating a GameObjects transform to compass direction on a given axis
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateAxisOnCompass : MonoBehavior
{
enum Axis { x, y, z }
[SerializeField] private Axis rotateAxis;
[SerializeField] private float compassSmooth;
private float lastMagneticHeading;
private void Start()
{
Input.location.Start();
Input.compass.enabled = true;
}
void Update()
{ //do rotation based on compass
float currentMagneticHeading = Mathf.Round(Input.compass.magneticHeading);
if (lastMagneticHeading < currentMagneticHeading - compassSmooth || lastMagneticHeading > currentMagneticHeading + compassSmooth)
{
lastMagneticHeading = currentMagneticHeading;
switch (rotateAxis)
{
case Axis.x:
transform.localRotation = Quaternion.Euler(lastMagneticHeading , 0 , 0);
break;
case Axis.y:
transform.localRotation = Quaternion.Euler(0 , lastMagneticHeading, 0);
break;
case Axis.z:
transform.localRotation = Quaternion.Euler(0 , 0, lastMagneticHeading);
break;
}
}
}
}
//MIT License
//Copyright(c) 2019 Ryan Wilson
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment