黄本読んだら傾きは加速度センサーを使って取るのが簡単って書いてあった。
ジャイロセンサー使うものはプラグインが必要とかなんとか?よく読んでない。
とりあえず加速度センサー使うとどんな感じでとれるのかやってみる。
傾き取得サンプルの作成
プロジェクト作成
こちらを参照。それっぽく名前を付ける。
![]() |
| プロジェクトができた |
スクリプト追加
Projectビュー→Create→C# Script
適当に名前を付ける。
![]() |
| スクリプト追加 |
スクリプト編集
ごりごりと。
![]() |
| やっぱC#楽だ・・・ |
こんな感じ
using UnityEngine;
using System.Collections;
public class InputCheck : MonoBehaviour
{
/// <summary>加速度?傾き?</summary>
private Vector3 acceleration;
/// <summary>フォント</summary>
private GUIStyle labelStyle;
// Use this for initialization
void Start()
{
//フォント生成
this.labelStyle = new GUIStyle();
this.labelStyle.fontSize = Screen.height / 22;
this.labelStyle.normal.textColor = Color.white;
}
// Update is called once per frame
void Update()
{
//文字描画はOnGUIでしかできないらしいので保持
this.acceleration = Input.acceleration;
}
/// <summary>
/// GUI更新はここじゃないとダメらしいよ。
/// まだよくわかんない。
/// </summary>
void OnGUI()
{
if (acceleration != null)
{
float x = Screen.width / 10;
float y = 0;
float w = Screen.width * 8 / 10;
float h = Screen.height / 20;
for (int i = 0; i < 3; i++)
{
y = Screen.height / 10 + h * i;
string text = string.Empty;
switch (i)
{
case 0://X
text = string.Format("accel-X:{0}", System.Math.Round(this.acceleration.x, 3));
break;
case 1://Y
text = string.Format("accel-Y:{0}", System.Math.Round(this.acceleration.y, 3));
break;
case 2://Z
text = string.Format("accel-Z:{0}", System.Math.Round(this.acceleration.z, 3));
break;
default:
throw new System.InvalidOperationException();
}
GUI.Label(new Rect(x, y, w, h), text, this.labelStyle);
}
}
}
}
- Input.accelerationで加速度センサーの入力が取れる(らしい)
- 定期的にUpdateが呼ばれる。
- 文字の表示とかGUIを操作するのはOnGUI()じゃないとダメ。
- GUI.Label()メソッドで文字を表示できる。
- Labelのフォント変更とかはGUIStyleを渡す。
ゲームオブジェクト追加
スクリプト単体じゃ何も起きないのでオブジェクトを追加。
でも見た目に出る必要ないから空のオブジェクトを追加
空のオブジェクトはHierarchy→Createでは作れないらしい。
空のオブジェクトはHierarchy→Createでは作れないらしい。
GameObject→Create Empty
![]() |
| 空のオブジェクトを追加 |
これも適当に名前つけとく。
オブジェクトにスクリプトを適用
ドラッグ&ドローップ![]() |
| オブジェクトにスクリプトを適用 |
![]() |
| 表示された |
実機で実行
方法はこっちに書いた感じ。![]() |
| 実機で動かした |
- 机に置いた状態だと X≒0、Y≒0、Z≒-1
ここを基準にして
- 手前に向かって立てていくと X0→0、Y0→-1、Z-1→0
- 奥に向かって立てていくと X0→0、Y0→1、Z-1→0
- 左に向かって立てると X0→-1、Y0→0、Z→0
- 右に向かって立てると X0→1、Y0→0、Z→0
ちゃんと取れてるっぽい・・・かな?






