1. 通过移动鼠标旋转摄像机观察模型

效果预览:

1. 通过移动鼠标旋转摄像机观察模型

代码:

using UnityEngine;
using System.Collections;

public class look_mode : MonoBehaviour {

    //摄像机参照的模型
    public Transform target;

    //摄像机距离模型的默认距离
    public float distance=20.0f;

    //鼠标在x轴和y轴方向移动的角度
    float x;
    float y;

    //限制旋转角度的最小值与最大值
    float yMinLimit=-20.0f;
    float yMaxLimit=80.0f;

    //鼠标在x和y轴方向移动的速度
    float xSpeed=250.0f;
    float ySpeed=120.0f;

    void Start()
    {
        //初始化x和y轴角度,使其等于参照模型的角度
         Vector2 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;
        if(rigidbody)    
            rigidbody.freezeRotation=true;        
    }

    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);
            Quaternion rotation =Quaternion.Euler(y,x,0);
            Vector3 position=rotation*new Vector3(0.0f,0.0f,-distance)+target.position;
            //设置摄像机的位置与旋转
              transform.rotation=rotation;
            transform.position=position;
        }
    }
    float ClampAngle(float angle,float min,float max)
    {
        if (angle < -360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp (angle, min, max);
    }
}

注意点:①将脚本(look_mode)赋给Camera

            ②将被观察者对象(Cube)赋给Target

1. 通过移动鼠标旋转摄像机观察模型