public class MouseOrbit : MonoBehaviour {
public Transform target ;
public float distance = 10.0f;
//摄像头距离target的距离,也可以动态的进行调节
public float xSpeed = 250.0f;
public float ySpeed = 120.0f;
//这两个值时再程序运行时慢慢调节出来的,你可以根据你想要的效果来进行适当的调节
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
//限制摄像头的仰角在-20°到80°之间
private float x = 0.0f;
private float y = 0.0f;
void Start () {
Vector3 angles = transform.eulerAngles;//获取
x = angles.y;
y = angles.x;
if (rigidbody){
rigidbody.freezeRotation = ***e;
}
}
void LateUpdate () {
if (target)
{
x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;//获取鼠标左键的偏移量,并对其大小进行规范化
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
y = ClampAngle(y, yMinLimit, yMaxLimit);//由于我们需要鼠标竖直方向移动时的角度可能大于360°,所以调用了这个工具函数。
var rotation = Quaternion.Euler(y, x, 0);//求得旋转角,
var position = rotation * (new Vector3(0.0f, 0.0f, -distance)) + target.position;
transform.rotation = rotation;
transform.position = position;
}
}
static float ClampAngle ( float angle,float min ,float max ) {//工具函数,专门用来限制angle的值在min与max之间
if (angle < -360f)
angle += 360f;
if (angle > 360f)
angle -= 360f;
return Mathf.Clamp (angle, min, max);
}
}