0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unityで対象を中心に縦横二方向に回るカメラ回転[Unity備忘録]

Last updated at Posted at 2022-07-13

はじめに

Unityで対象を中心にした回転、単純にRotateAroundすると、一方向だけならいいんですが、縦横二方向になるときもいことになります。
じゃあどうすんねんってなった時の僕の回答です。多分公式リファレンスとか調べたらもっと賢い方法あるんだろうなあ。

_transformを_centerを中心に、centerを向きながら回転させる関数。カメラの距離も決めちゃってるよ。

    public float cameraDistance = 1f;

    #region MyRotateAround関数のローカルパラメータ。他のとこからいじっちゃダメ。
    Vector3 _pos;
    float _ypos = 0f;
    const float _yLimit = 0.9f;
    #endregion

    void MyRotateAround(Transform _transform, Vector3 _center, Vector2 angle)
    {
        //カメラの上下はy座標の移動+LookAt,左右はRotateAroundで行う
        //左右
        _transform.RotateAround(_center, Vector3.up, angle.x);
        //上下のパラメータの計算
        _ypos += angle.y * 0.02f;
        if (_ypos > _yLimit * cameraDistance) _ypos = _yLimit * cameraDistance;
        else if (_ypos < -_yLimit * cameraDistance) _ypos = -_yLimit * cameraDistance;
        //位置を代入用変数に入れて、上下のパラメータを適用し、距離の調整をする
        _pos = _transform.position;
        _pos.y = _center.y + _ypos;
        _pos =(_pos-_center).normalized * cameraDistance+_center;
        //代入用変数を代入する。
        _transform.position = _pos;
        //対象に向かせる
        _transform.LookAt(_center);
    }

中心を動かす場合のスクリプト

    public void ChangeCenter(Vector3 newPosition)
    {
        newPosition = newPosition - center;
        center += newPosition;
        transform.position += newPosition;
    }

余談

メモリが少しでも増えないように、ローカル変数を外に出してます。多分最適化で何とかしてくれるのかもしれないけれど?
テストスクリプトは、テスト内容を日本語で書くようにしてるんですよねえ。プロジェクトの中に「Test_Camer...」(...以降は折りたたまれて見えない)みたいなスクリプトがあっても二度と開きませんしね。重要な組み込み用のプログラムと見分けがつきやすいしいいですよ?

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?