LoginSignup
10
12

More than 5 years have passed since last update.

UnityでiOSのコンパスにアクセスする

Posted at

Inputクラスからコンパスの向きを検出できる。よく似た機能のGPSとは使い方が違うのでハマってしまった。

GPSの場合は公式のサンプルにもあるようにLocationService.Startを呼び、タイムアウトなどを扱う事で緯度経度にアクセスできるという仕組み。

LocationService.Start

GPSを使う例
function Start () {
        // First, check if user has location service enabled
        if (!Input.location.isEnabledByUser)
            return;
        // Start service before querying location
        Input.location.Start ();
        // Wait until service initializes
        var maxWait : int = 20;
        while (Input.location.status
               == LocationServiceStatus.Initializing && maxWait > 0) {
            yield WaitForSeconds (1);
            maxWait--;
        }
        // Service didn't initialize in 20 seconds
        if (maxWait < 1) {
            print ("Timed out");
            return;
        }
        // Connection has failed
        if (Input.location.status == LocationServiceStatus.Failed) {
            print ("Unable to determine device location");
            return;
        }
        // Access granted and location value could be retrieved
        else {
            print ("Location: " + Input.location.lastData.latitude + " " +
                   Input.location.lastData.longitude + " " +
                   Input.location.lastData.altitude + " " +
                   Input.location.lastData.horizontalAccuracy + " " +
                   Input.location.lastData.timestamp);
        }
        // Stop service if there is no need to query location updates continuously
        Input.location.Stop ();
    }

コンパスの場合はStartメソッドは無く、enabledにtrueを代入するとコンパスから値を取得できるようになる。

コンパスを使うスクリプト
using UnityEngine;
using System.Collections;

public class ComRotate : MonoBehaviour {

    // Use this for initialization
    void Start () {
        Input.compass.enabled = true;
    }

    // Update is called once per frame
    void Update () {
        transform.rotation = Quaternion.Euler(0, -Input.compass.trueHeading, 0);
    }
}

iOSのバージョンによる違いやAndroidでどう動くのかなどは調べていません。

10
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
12