対象のオブジェクトを中心にしてカメラを回転させる処理を実装する
まず対象のオブジェクトの子オブジェクトに空オブジェクトを作成し、位置を対象と同じにする。
更にその子オブジェクトにメインカメラを配置する。
空オブジェクトに以下のスクリプトをアタッチする
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class RotateCamera : MonoBehaviour { | |
public int maxAngle = 60; //垂直方向に回転できる上限角度 | |
public int minAngle = 359; //垂直方向に回転できる下限角度 | |
public float speed = 360.0f; //回転速度(角度/秒) | |
void Start() { | |
} | |
void Update() { | |
//入力から回転を取得(Horizontal2、Vertical2はコントローラーのスティックを割り当て) | |
float horizontal = Input.GetAxis("Horizontal2") * speed * Time.deltaTime; | |
float vertical = Input.GetAxis("Vertical2") * speed * Time.deltaTime; | |
//入力があった場合、その方向へ回転させる | |
if (Input.GetAxis("Horizontal2") != 0 || Input.GetAxis("Vertical2") != 0) { | |
//水平方向に回転させる(水平方向はワールド軸) | |
this.transform.Rotate(0, horizontal, 0, Space.World); | |
//垂直方向は90度以上回転しないよう制限する | |
if (this.transform.localEulerAngles.x + vertical <= maxAngle || | |
this.transform.localEulerAngles.x + vertical >= minAngle) { | |
//垂直方向に回転させる(垂直方向はローカル軸) | |
this.transform.Rotate(vertical, 0, 0, Space.Self); | |
} | |
} | |
} | |
} |
カメラではなく、カメラの親オブジェクトを回転させる事で、対象のオブジェクトの周りを回転できるようにしている
水平軸の回転はワールド軸にして、y軸を中心に回転させることがポイント