摄像机旋转


/*
    [0] 获得相机左右旋转的角度(处理X)
    [1] 获得相机左右旋转的角度(处理Y)
 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class CameraRotate : MonoBehaviour
{

    [Tooltip("x灵敏度")]
    public float sensitivityX = 3F;
    [Tooltip("y灵敏度")]
    public float sensitivityY = 5F;

    [Tooltip("上最大视角")]
    public float minimumY = -60F;
    [Tooltip("下最大视角")]
    public float maximumY = 60F;

    private float rotationX = 0F;
    private float rotationY = 0F;


    private void Awake()
    {
        var angle = transform.localEulerAngles;
        rotationX = angle.x;
        rotationY = angle.y;
    }

    //针对摄像机加了PhysicsRaycaster后使用EventSystem.current.IsPointerOverGameObject, 3D物体也会返回true的情况
    bool IsPointerOverGameObject(out List<RaycastResult> results)
    {
        PointerEventData pointerData = new PointerEventData(EventSystem.current);
        pointerData.position = Input.mousePosition;
        results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(pointerData, results);
        return results.Count > 0;
    }

    private bool isDrag = false;
    private List<RaycastResult> results;
    private void Update()
    {
        if(isDrag && !Input.GetMouseButton(0)){
            isDrag = false;
        }
        if (Input.GetMouseButtonDown(0))
        {
            if (IsPointerOverGameObject(out results) && results[0].gameObject.layer == 5) return;
            isDrag = true;
        }
        if (isDrag)
        {
            //! [0]
            rotationX = transform.localEulerAngles.y - Input.GetAxis("Mouse X") * sensitivityX;
            //! [1]
            rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);
            transform.localEulerAngles = new Vector3(rotationY, rotationX, 0);

        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_17813937/article/details/80109119