Unity 摄像机视角控制的介绍

1. 摄像机预览物体 上下左右远近

把CameraFollow脚本赋给Camera,把要观察的对象赋给target

using UnityEngine;
using System.Collections;
 
public class CameraFollow : MonoBehaviour
{
    public Transform target;
    public float targetHeight;
    public float distance;
    public int maxDistance;
    public float minDistance;
    public float xSpeed;
    public float ySpeed;
    public int yMinLimit;
    public int yMaxLimit;
    public int zoomRate;
    public float rotationDampening;
    private float x;
    private float y;
 
    public CameraFollow()
    {
        this.targetHeight = 2f;
        this.distance = 5f;
        this.maxDistance = 20;
        this.minDistance = 2.5f;
        this.xSpeed = 250f;
        this.ySpeed = 120f;
        this.yMinLimit = -20;
        this.yMaxLimit = 80;
        this.zoomRate = 20;
        this.rotationDampening = 3f;
    }
    public void Start()
    {
        Vector3 eulerAngles = this.transform.eulerAngles;
        this.x = eulerAngles.y;
        this.y = eulerAngles.x;
        if (this.rigidbody)
        {
            this.rigidbody.freezeRotation = true;
        }
    }
    public void LateUpdate()
    {
        if (this.target)
        {
            if (Input.GetMouseButton(1) || Input.GetMouseButton(1))
            {
                this.x += Input.GetAxis("Mouse X") * this.xSpeed * 0.02f;
                this.y -= Input.GetAxis("Mouse Y") * this.ySpeed * 0.02f;
            }
            else
            {
                if (Input.GetAxis("Vertical") != (float)0 || Input.GetAxis("Horizontal") != (float)0)
                {
                    float num = this.target.eulerAngles.y;
                    float num2 = this.transform.eulerAngles.y;
                    this.x = Mathf.LerpAngle(num2, num, this.rotationDampening * Time.deltaTime);
                }
            }
            this.distance -= Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * (float)this.zoomRate * Mathf.Abs(this.distance);
            this.distance = Mathf.Clamp(this.distance, this.minDistance, (float)this.maxDistance);
            this.y = ClampAngle(this.y, (float)this.yMinLimit, (float)this.yMaxLimit);
            Quaternion quaternion = Quaternion.Euler(this.y, this.x, (float)0);
            Vector3 position = this.target.position - (quaternion * Vector3.forward * this.distance + new Vector3((float)0, -this.targetHeight, (float)0));
            this.transform.rotation = quaternion;
            this.transform.position = position;
        }
    }
    public  float ClampAngle(float angle, float min, float max)
    {
        if (angle < (float)-360)
        {
            angle += (float)360;
        }
        if (angle > (float)360)
        {
            angle -= (float)360;
        }
        return Mathf.Clamp(angle, min, max);
    }
     
}

 

未经允许不得转载:第一Unity3D » Unity 摄像机视角控制的介绍

赞 (0)