unity摄像机旋转缩放功能

using UnityEngine;

public class CameraController : MonoBehaviour
{

    public float maxScroll = 2;
    public float minScroll = 10;
    public float maxYRotateAngles = 80;
    public float minYRotateAngles = 10;
    public float rotateSpeed = 5;
    public float scrollSpeed = 10;

    public Transform targetTransform;
    private Vector3 offsetPlayerPos;
    private float distance;
    private Quaternion currentRotation;

    void Start()
    {
        transform.LookAt(targetTransform);
        offsetPlayerPos = transform.position - targetTransform.position;
    }


    void Update()
    {
        transform.position = targetTransform.position + offsetPlayerPos;
        RotateCamera();
        ScrollView();
    }
    void RotateCamera()
    {
        if (Input.GetMouseButton(1))
        {
            //向右滑动时正值,向左滑动是负值。
            transform.RotateAround(targetTransform.position, targetTransform.up, rotateSpeed * Input.GetAxis("Mouse X"));
            Vector3 originalPos = transform.position;
            Quaternion originalRotation = transform.rotation;
            transform.RotateAround(targetTransform.position, transform.right, -rotateSpeed * Input.GetAxis("Mouse Y"));//影响的属性有两个,position,rotation;
            //限制摄像机垂直滑动的距离;
            float x = transform.eulerAngles.x;
            if (x < minYRotateAngles || x > maxYRotateAngles)//当超出范围之后,我们将属性归位原来的,就是让旋转⽆效;
            {
                transform.position = originalPos;
                transform.rotation = originalRotation;
            }

            offsetPlayerPos = transform.position - targetTransform.position;
        }
    }
    void ScrollView()
    {
        //限制最大缩放
        if (Input.GetAxis("Mouse ScrollWheel") < 0 && offsetPlayerPos.magnitude < maxScroll)
        {
            //获取偏移量的模
            distance = offsetPlayerPos.magnitude;
            distance += System.Math.Abs(Input.GetAxis("Mouse ScrollWheel")) * scrollSpeed;
            //通过获得单位向量*新的偏移模更新偏移信息
            offsetPlayerPos = offsetPlayerPos.normalized * distance;
        }
        //限制最小缩放
        if (Input.GetAxis("Mouse ScrollWheel") > 0 && offsetPlayerPos.magnitude > minScroll)
        {
            //获取偏移量的模
            distance = offsetPlayerPos.magnitude;
            distance += -System.Math.Abs(Input.GetAxis("Mouse ScrollWheel")) * scrollSpeed;
            //通过获得单位向量*新的偏移模更新偏移信息
            offsetPlayerPos = offsetPlayerPos.normalized * distance;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值