I am using Unity’s Compass module to align a real time map in AR to North, so that it will line up in the real world. However while it works it is giving me very inconsistent results. Every time I open it it points somewhere new. The code I am using is below:
public Transform target;
public void Start()
{
Input.compass.enabled = true;
Input.location.Start();
target.rotation = Quaternion.Euler(0, -Input.compass.trueHeading, 0);
}
Where “target” is the transform of the map object.
Setting the rotation of your AR object is not enough to align its orientation with real-world orientation.
Every time you start your AR Session, the AR subsystem coordinates (and orientation) will be different. ARSessionOrigin has a specific method for this kind of situations:
FindObjectOfType().MakeContentAppearAt(targetTransform, position, rotation);
Calling this method will not change the actual position and rotation of your target object, but will make it APPEAR to be placed at the desired position and orientation.
Thanks for the help, I got it to work for what I wanted! I need to do a bit of work to iron out the jittereryness of the compass. For anyone else here is the code I used using AR Foundation where target is the object to be aligned with North:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace UnityEngine.XR.ARFoundation
{
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
using UnityEngine.UI;
public class Compass : MonoBehaviour
{
private GameObject aRSessionOrigin;
public GameObject target;
public Transform targetTransform;
private GameObject sign2;
// Start is called before the first frame update
void Start()
{
Input.compass.enabled = true;
Input.location.Start();
aRSessionOrigin = GameObject.Find("AR Session Origin");
var aRScript = aRSessionOrigin.GetComponent<ARSessionOrigin>();
aRScript.MakeContentAppearAt(targetTransform, targetTransform.position, Quaternion.Euler(0, -Input.compass.trueHeading, 0));
//aRSessionOrigin.MakeContentAppearAt(target, target.position, Quaternion.Euler(0, -Input.compass.trueHeading, 0));
//FindObjectOfType<ARSessionOrigin>().MakeContentAppearAt(target, target.position, Quaternion.Euler(0, -Input.compass.trueHeading, 0));
}
// Update is called once per frame
void Update()
{
aRSessionOrigin = GameObject.Find("AR Session Origin");
var aRScript = aRSessionOrigin.GetComponent<ARSessionOrigin>();
aRScript.MakeContentAppearAt(targetTransform, targetTransform.position, Quaternion.Euler(0, -Input.compass.trueHeading, 0));
sign2 = GameObject.Find("Text2");
var sign2text = sign2.GetComponent<Text>();
sign2text.text = Input.compass.trueHeading.ToString();
}
}
}