マウスで視点変更できるカメラ

targetにカメラで追尾したい対象をドロップしておく
対象とカメラの位置の相対的距離をoffsetとして記録しておいて、
対象が動いても、それを維持するようにカメラも移動する
(固定なので遅れはない)


using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {
	public Transform target;
	private float speed=0.5f;
	private float smoothing = 5f;
	Vector3 offset;    
	float xSpeed = 450f;
 	float ySpeed = 120f;
	float yMinLimit = -20;
	float yMaxLimit = 80;
	float x=0;
	float y=0;

	void Start () {
		offset = transform.position - target.position;	
		Vector3 angles = transform.eulerAngles;
		x = angles.y;
		y = angles.x;
	}

	void Update () {
         x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
  //      y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
 //		y = ClampAngle(y, yMinLimit, yMaxLimit);
 		Quaternion rot = Quaternion.Euler( new Vector3(y, x, 0) );
		rot.x=0;rot.z=0;
		target.rotation    = rot;
		transform.rotation = rot;
		transform.position = rot*offset + target.position;
	}
}

タグ:

unity
最終更新:2015年05月26日 19:29