Unity 一个简单的鼠标跟随

  这份代码主要是根据鼠标在屏幕上的移动来操作摄像机

using UnityEngine;
using System.Collections;

public class LookAt:MonoBehaviour{
         public Transform target;//摄像机跟随目标
         public float distance;//摄像机跟随距离
         public Vector2 mouseAngles;//鼠标在屏幕上的位置
         public float yrotationMin;
         public float yrotationMax;
         public float xspeed;
         public float yspeed;

         void Start(){
                mouseAngles.x=this.target.eulerAngles.x;
                mouseAngles.y=this.target.eulerAngles.y;
                distance=3;
                xspeed=200;
                yspeed=100;
                yrotationMax=60;
                yrotationMin=-30;
         }
  
          void LateUpdate(){
                 if(target){
                        mouseAngles.x+=Input.GetAxis("Mouse X")*xspeed*0.02f;
                        mouseAngles.y+=Input.GetAxis("Mouse Y")*yspeed*0.02f;
                        mouseAngles.y=transformAngle(mouseAngles.y,yrotationMin,yroataionMax);
                         Quaternion rotation=Quaternion.Euler(mouseAngles.y,mouseAngles.x,0);
                          //下面代码的作用为 使摄像机朝向目标 并在目标后方distance米处
                          Vector3 position=rotation*new Vector3(0.0f,0.0f,-distance)+target.position;
                          this.transform.rotation=rotation;
                          this.transform.position=position;
                 }
          }

         float transformAngle(float angle,float min,float max){
                if(angle<-360)angle+=360;
                if(angle>360)angle-=360;
                return Mathf.Clamp(angle,min,max);  
         }
}
原文地址:https://www.cnblogs.com/He-Jing/p/3792615.html