VRで部屋の中を自由に動き回りたかったので、まずはUnity単独で部屋の中を動き回れるアプリを作る。
部屋を作って入る
まずは適当に新規プロジェクトを作ります。
自前で部屋を組み立てるのは大変だるいので、Asset Storeからimportします。今回はPack Gesta Furniture #1 - Asset StoreというAssetを使用します。
ちなみにGoogleでAsset Storeと欲しいシーンをキーワードに入れて検索すれば色々見つかる。FPS用のマップとか、VR定番のゾンビとか色々揃ってて至れり尽くせり。
Unity用無料3DモデルAsset 100個まとめ - NAVER まとめ
例によってAsset Storeで検索して、Download/Importします。相変わらず時間かかる。
Importが済んだら、Assetsの中にFurniture_ges1というフォルダが出来るのでscene
とかをポチポチしてたらなんかアプリに適用された。
Build And Runしてみと、3Dの部屋の中入ることが出来ます。簡単。
スクショ取りそこねたスマン。
部屋の中にプレイヤーを設置
なかなか苦戦した。
まずははじめてのUnity - Unityのチュートリアルのときやったことを思い出し、MainPlayerオブジェクトを置きます。
今回はプレイヤーは不可視で良いのでHierarchy -> Create -> Create Empty
します。
PositionをX:0, Y:1, Z:5
、RotationをX:0, Y:90, Z:5
に設定。
このままだと床を突き抜けて永久に落下するので、MainPlayer
にRigidbody
とBox Colider
をAdd Component
します。設定値はとりあえずデフォルトでOK。
あと床の方も同様にBox Colider
をAdd Component
する。床はHierarchy -> scene -> Models -> interior -> Plane001
にある。
ここまで出来たらプレイヤーが床を突き抜けなくなる。
続いて追従するカメラを設定する。これもチュートリアルと同じ要領でOK。
元々Camera
オブジェクトは存在してるので、PositionをX:0, Y:2, Z:0
、RotationをX:0, Y:0, Z:0
にして、Hierarchy
からMainPlayer
にドラッグ&ドロップする。
Camera
オブジェクトにSciprt
をAdd Component
する。
FollowPlayer.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FllowPlayer : MonoBehaviour { public Transform target; // ターゲットへの参照 private Vector3 offset; // 相対座標 void Start () { //自分自身とtargetとの相対距離を求める offset = GetComponent<Transform>().position - target.position; } void Update () { // 自分自身の座標に、targetの座標に相対座標を足した値を設定する GetComponent<Transform>().position = target.position + offset; } }
VRオレの部屋できたー!!
部屋の中を移動できるようする
ここはチュートリアル通りにはいかなかった。BoxColider
とRigidbody
でAddForce
すると立方体がころころ転がってしまう。Freeze Rotation
をチェックすれば回転しなくなるが、AddForce
ではカメラ視点で進行方向に進むのが難しかったので別のやりかたにする。
MainPlayer
オブジェクトにScript
をAdd Component
します。
MainPlayerController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainPlayerController : MonoBehaviour { public float speed = 10; void FixedUpdate () { // 左右キー入力に応じて回転速度を決定 float speed = 0.0f; if (Input.GetKey(KeyCode.LeftArrow)) { speed += -90.0f; } if (Input.GetKey(KeyCode.RightArrow)) { speed += 90.0f; } // Y軸(Vector3.up)周りを1フレーム分の角度だけ回転させるQuaternionを作成 Quaternion rot = Quaternion.AngleAxis(speed * Time.deltaTime, Vector3.up); // 元の回転値と合成して上書き transform.localRotation = rot * transform.localRotation; if (Input.GetKey (KeyCode.UpArrow)) transform.Translate( Vector3.forward * 0.1f); if (Input.GetKey (KeyCode.DownArrow)) transform.Translate( Vector3.back * 0.1f); } }
これで左右キー入力でプレイヤーの向きを変えて、上下キーで前進・後退出来るようになりました!!
ちなみにColider
を設定していないオブジェクトもあるので、壁とか突き抜けちゃいます。