2012年02月26日

[Unity] Unityで位置情報を取得する

Androidを使っているからこそ位置情報を使ったアプリを作ってみたくなるものですが、
Input.location の情報を表示するには前準備が必要です。

その方法は以下のリファレンスにある通りですが、
自分なりにコメントをつけ直してみました。

Unity リファレンス
http://unity3d.com/support/documentation/ScriptReference/LocationService.Start.html

このサンプルを知る前までは、前準備が必要だとは知らず「なぜいつも0しか表示されないんだろう」
と困っていました。
----------------------------------
function Start() {
// サービスが有効かチェック
if (!Input.location.isEnabledByUser) {
return;
}
Debug.Log("isEnabledByUser --> OK");

// ロケーションを問合せる前にInput.locationをスタート
Input.location.Start();
Debug.Log("location.Start()");

// 初期化できるまで待つ
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;
}
Debug.Log("service initializes --> success");

// 接続状況
if (Input.location.status == LocationServiceStatus.Failed) {
print("Unable to determine device location");
return;
} else {
// Access granted and location value could be retrieved
Debug.Log("Location: " + Input.location.lastData.latitude + " " + // 緯度
Input.location.lastData.longitude + " " + // 経度
Input.location.lastData.altitude + " " + // 標高
Input.location.lastData.horizontalAccuracy + " " + // 水平精度
Input.location.lastData.verticalAccuracy + " " + // 垂直精度
Input.location.lastData.timestamp); // タイムスタンプ
}
Debug.Log("Connection --> OK");

// Stop service if there is no need to query location updates continuously
Input.location.Stop();
Debug.Log("Service --> Stop");
}
----------------------------------
位置情報を得るにはAndroid側から取得しようかと思っていただけに、
Unityだけで完結できるのは嬉しいです。

カメラ、ジャイロ、加速度、コンパス、位置情報、マイク、ジョイスティック(Honeycomb 3.1以降)。
Unityだけで取得できる入力情報がかなり揃ってきました。

Android側との連携部分で色々と工数をかけてしまっていたので嬉しいです。
今後のバージョンアップでも他のセンサー(温度、輝度、近接等)との連携が
されることを期待してます。


■補足
端末の設定で、位置情報の取得を許可していないと
Input.location.isEnabledByUser が false を返し続けます。

許可するためには、
端末のメニューボタン > 設定 > 位置情報とセキュリティ > 無線とネットワークをオン
にしましょう↓

201202026LocationSetting.png
posted by be-style at 02:51| Comment(0) | Unity
この記事へのコメント
コメントを書く
お名前:

メールアドレス:

ホームページアドレス:

コメント: [必須入力]