【Unity】シンプルなヴァーチャルカメラを用意する
Cinemachine のインストール
- Window > Package Manager から Cinemachine をインストールする
Virtual Camera の設定
- Cinemachine > Virtual Camera を追加する
※Virtual Camera を追加すると Main Camera に CinemachineBrain が追加される
- 追加された Virtual Camera を下記の設定にする
CinemachineVirtualCamera の Body を Orbital Transposer にする Binding Mode を Simple Follow With World Up にする Follow と LookAt に追跡対象を指定する
スクリプトの追加
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public Camera mainCamera; public float Speed = 10.0f; void Update() { if (mainCamera == null) { return; } // ユーザー入力の取得 var doMove = false; var direction = Vector3.zero; if (Input.GetKey(KeyCode.A)) { direction.x -= 1.0f; doMove = true; } if (Input.GetKey(KeyCode.D)) { direction.x += 1.0f; doMove = true; } if (Input.GetKey(KeyCode.W)) { direction.z += 1.0f; doMove = true; } else if (Input.GetKey(KeyCode.S)) { direction.z -= 1.0f; doMove = true; } if (doMove) { // 移動方向の決定 var move = mainCamera.transform.rotation * direction; move.y = 0.0f; // XZ 平面成分のみ適用 move.Normalize(); // 移動 transform.position += move * Speed * Time.deltaTime; // キャラクターの向き transform.rotation = Quaternion.LookRotation(move); } } }