Perl日記

日々の知ったことのメモなどです。Perlは最近やってないです。

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));
        }
    }
}

f:id:rightgo09:20191112233958j:plain
最初はまっすぐになってる
f:id:rightgo09:20191112233110j:plain
斜めになった

一度オイラー角に変換してから 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;
        }
    }
}

f:id:rightgo09:20191112234144j:plain
Z は 0 のまま


これをカメラにアタッチして、写真を撮るカメラにくっつけて、カメラっぽく動かせるようにして遊んでみてた。

f:id:rightgo09:20191112235341g:plain


参考:
bluebirdofoz.hatenablog.com