Unity で Rotation の Z を動かさずに回転する
メモ。
入力に応じてオブジェクトを回転させたいときは、Transform.Rotate() を使う。
しかし、二次元的にそれをそのまま x と y に当てはめていろいろ動かすと、どんどん斜めになってしまう。
カメラ用のスクリプト CameraController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { void Update() { float x = Input.GetAxis("Vertical"); float y = Input.GetAxis("Horizontal"); if (x != 0 || y != 0) { x = -1 * x * Time.deltaTime * 50f; y = y * Time.deltaTime * 50f; this.transform.Rotate(new Vector3(x, y, 0)); } } }
一度オイラー角に変換してから x と y を加算減算して、またクオータニオンに変換して transform.rotation に代入するといいようだ。
(正直完全に理解してない)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { void Update() { float x = Input.GetAxis("Vertical"); float y = Input.GetAxis("Horizontal"); if (x != 0 || y != 0) { x = x * Time.deltaTime * 50f; y = y * Time.deltaTime * 50f; Quaternion rotation = this.transform.rotation; Vector3 rotationAngles = rotation.eulerAngles; rotationAngles.x = rotationAngles.x - x; rotationAngles.y = rotationAngles.y + y; rotation = Quaternion.Euler(rotationAngles); this.transform.rotation = rotation; } } }
これをカメラにアタッチして、写真を撮るカメラにくっつけて、カメラっぽく動かせるようにして遊んでみてた。