LoginSignup
10
11

More than 5 years have passed since last update.

【Unity】Android端末のジャイロセンサーを使ってボールを転がすメモ

Last updated at Posted at 2016-07-18

スクリーンショット 2016-07-18 2.15.09.png

やりたいこと

  • スマホを傾けてアプリの中のボールを転がしたい
  • スマホを机に置いた状態が水平であってほしい

とりあえず実装

参考

できた。

さらにやりたいこと

  • directional lightも傾きに合わせて動かしたい

とりあえず実装

参考
- Unity スクリプトリファレンス Gyroscope

ライトに直接スクリプトを貼って簡単じゃーん(?)

・・・何か違う

  • 想定通りに影が変わらない軸がある
  • どうやらAndroid端末のジャイロは、手に持ち、通話中の状態を基準と想定している?
  • Unity上とAndroid端末のy軸とz軸が逆っぽい

yとzを入れ替える

できた。ソースは後述。

もうひとつやりたいこと

  • このままだと直射日光は垂直にしか当たらないので、適当に傾けたい

シーンで設定しているライトの向きをオフセットとして使う

  • transform.rotation の値の型は Quaternion
  • Quaternion同士を掛け算すると向きを合成できる

というわけで、以下のコードに。

gyro_to_light.cs

public Quaternion direction_light_offset;
public Quaternion gyro_to_light;

void Start () {
    // 太陽光の傾きオフセットをシーンの設定から保持
    direction_light_offset = this.transform.rotation;
}

void Update () {
    // 端末の傾きを保持
    gyro_to_light = Input.gyro.attitude;
    // yz軸の値を入れ替え
    float yz_change;
    yz_change = gyro_to_light.y;
    gyro_to_light.y = gyro_to_light.z;
    gyro_to_light.z = yz_change;
    // ライトの向きを端末の傾き+元の設定のオフセットで変更
    this.transform.rotation = gyro_to_light * direction_light_offset;
}

できた。

Quaternionについての参考はこちら
UnityのベクトルとQuaternionによる回転について / テラシュールブログ

10
11
1

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
11