LoginSignup
18
23

More than 5 years have passed since last update.

UnityでVRを触ってみた 〜歩行編〜

Posted at

はじめに

VR作りたくて、Unityで試行錯誤して何とか動いたのでそのまとめ3です。
今回はVRの中で歩行(カメラを前進させる)をしてみたいと思います。

今回はコントローラーはなくHMDだけの状況です。
ですので、歩行を始めるトリガーとなるものは目線(カメラ)を下に傾けたときにしました。

以前の記事
- UnityでVRを触ってみた 〜導入編〜
- UnityでVRを触ってみた 〜視点の検知編〜

環境

  • Mac OSX v10.11
  • Google VR SDK v0.8
  • Unity v5.3.5

いざ開発!

1. 空のオブジェクトにScriptを追加

メニューから[GameObject] -> [Create Empty]を選び、GameObjectがSceneに追加されたことを確認します。
追加されたGameObjectにNew ScriptをAdd Componentします。

gameobject_script.png

2. Scriptを書いて実装する

次に、Scriptを書いてカメラを前進させてみたいと思います。
手順としては以下の通りです。
① 毎フレームカメラの角度を取得する
② ある角度であればカメラを前進させる


using UnityEngine;
using System.Collections;

public class GameScript : MonoBehaviour {
    public Camera mainCamera;
    public float moveSpeed  = 2.0f;
    public float moveAngleX = 20.0f;

    float yOffset;

    // Use this for initialization
    void Start () {
        yOffset = mainCamera.transform.position.y;
    }

    // Update is called once per frame
    void Update () {

        // 1.カメラの傾きを取得
        float x = mainCamera.transform.eulerAngles.x;
        Debug.Log (x);

        // 2.ある角度以内であれば前進させる
        if (moveAngleX < x && x < 90.0f) {
            moveFoward ();
        }
    }

    private void moveFoward() {
        Vector3 direction = new Vector3 (mainCamera.transform.forward.x, 0, mainCamera.transform.forward.z).normalized * moveSpeed * Time.deltaTime;
        Quaternion rotation = Quaternion.Euler (new Vector3 (0, -mainCamera.transform.rotation.eulerAngles.y, 0));
        mainCamera.transform.Translate (rotation * direction);
        mainCamera.transform.position = new Vector3 (mainCamera.transform.position.x, yOffset, mainCamera.transform.position.z);
    }
}

上のScriptを書いた後にInspectorビュー戻ると、Main Cameraが空になっているのでMain Cameraオブジェクトをドラッグ&ドロップで紐付けを行います。

MainCamera.png

3. 動かしてみる

再生ボタンを押して動かしてみましょう。

out.gif

歩きました!
角度と歩行スピードを変更したい場合は moveAngleX と moveSpeed をいじって調節してみてください。

18
23
2

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
18
23