Unity关于触摸屏相机视角的控制方式(鼠标也可操作)

  1. 触屏软件功能展示对于相机视角的控制使用
using UnityEngine;
using UnityEngine.EventSystems;

public class CameraController : MonoBehaviour
{
    public GameObject Target;
    public float LastY;
    public float Distance = 10f;
    public float MinDistance = 5f;
    public float MaxDistance = 15f;
    public float Sensitivity = 5f;
    public float MoveSensitivity = 3;
    public float rotationX = 0f;
    public float rotationY = 0f;
    public Vector3 offset;
    public Quaternion targetRotation;
    public Vector3 targetPosition;
    [Header("鼠标位移")]
    public bool IsDragging;
    private Vector3 lastPosition;
    [Header("点击跟随")]
    public bool IsMovingByObj = true;
    [Header("手势")]

    //旧的触摸点位置
    Vector2 oldPos1;
    Vector2 oldPos2;

    public float speed = 0.7f;

    public float RotaTouchHor = 0.7f;
   
    public BoxCollider moveBox;

    public BoxCollider TargetBox;

    public bool IsCanRota = true;

 

    private void Start()
    {
        offset = transform.position - Target.transform.position;
        //speed =4;
        //RotaTouchHor =4;
        TargetObjPos = Target.transform.position;
        
    }

 

 

    private void Update()
    {

        if (Input.touchCount < 2)
        {
            if (Input.touchCount > 0)
            {
                Touch touch = Input.GetTouch(0);
                if (touch.phase == TouchPhase.Moved)
                {
                    float touchDeltaPositionX = touch.deltaPosition.x;
                    float touchDeltaPositionY = touch.deltaPosition.y;
                    // Do something with the touchDeltaPositionX value, such as using it to rotate an object
                    rotationX += touchDeltaPositionX * speed;
                    rotationY -= touchDeltaPositionY * speed;
                    rotationY = Mathf.Clamp(rotationY, -90f, 89f);
                    targetRotation = Quaternion.Euler(rotationY, rotationX, 0f);
                }
            }
            if (Input.GetMouseButton(1) && Input.touchCount == 0 && !EventSystem.current.IsPointerOverGameObject())
            {

                IsDragging = true;
                lastPosition = Input.mousePosition;
            }

            if (Input.GetMouseButtonDown(1))
            {
 
            }
            if (Input.GetMouseButton(0) && Input.touchCount == 0 && !EventSystem.current.IsPointerOverGameObject())
            {
                if (IsCanRota)
                {
                    rotationX += Input.GetAxis("Mouse X") * Sensitivity;
                    rotationY -= Input.GetAxis("Mouse Y") * Sensitivity;
                    rotationY = Mathf.Clamp(rotationY, -90f, 89f);
                    targetRotation = Quaternion.Euler(rotationY, rotationX, 0f);
                }

            }
            if (Input.GetKey(KeyCode.X) && Input.touchCount == 0 && !EventSystem.current.IsPointerOverGameObject())
            {
                if (IsCanRota)
                {
                    //Debug.Log("XYZ");
                    rotationX -= 0.01f * Sensitivity;

                    rotationY = Mathf.Clamp(rotationY, -90f, 89f);
                    targetRotation = Quaternion.Euler(rotationY, rotationX, 0f);
                }

            }
            //if (Input.GetMouseButton(2) && !EventSystem.current.IsPointerOverGameObject())
            //{
            //    rotationX += 0.02f * Sensitivity;
            //    rotationY -= Input.GetAxis("Mouse Y") * Sensitivity;
            //    rotationY = Mathf.Clamp(rotationY, -90f, 85f);
            //    targetRotation = Quaternion.Euler(rotationY, rotationX, 0f);
            //}
            float TargetDistance = Distance - Input.GetAxis("Mouse ScrollWheel") * Sensitivity * 6F;

            Distance = Mathf.Lerp(Distance, TargetDistance, 0.7f);
            //Distance -= Input.GetAxis("Mouse ScrollWheel") * Sensitivity*2F;

            Distance = Mathf.Clamp(Distance, MinDistance, MaxDistance);

        }
        else if (Input.touchCount == 2)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved)
            {
                //新的触摸点的位置
                Vector2 newPos1 = Input.GetTouch(0).position;
                Vector2 newPos2 = Input.GetTouch(1).position;

                //判断触摸的手势是否为放大
                if (isEnLarge(oldPos1, oldPos2, newPos1, newPos2))
                {
                    //"Mouse ScrollWheel"++
                    Distance -= 0.2f * Sensitivity * RotaTouchHor;
                }
                else  //如果触摸手势为缩小 
                {
                    //--
                    Distance += 0.2f * Sensitivity * RotaTouchHor;
                }


                //新的位置覆盖旧的位置
                oldPos1 = newPos1;
                oldPos2 = newPos2;
            }
            //Vector3 position = targetRotation * new Vector3(0f, 0f, -Distance) + Target.transform.position;
        }


        Vector3 position = targetRotation * new Vector3(0f, 0f, -Distance) + Target.transform.position;
        if (position.y < LastY)
        {
            position.y = LastY;
        }

        if (Input.GetMouseButtonUp(1))
        {
            IsDragging = false;

        }
        targetPosition = position;
    }



    private void FixedUpdate()
    {



        Target.transform.position = Vector3.Lerp(Target.transform.position, TargetObjPos, Time.deltaTime * MoveSensitivity);
        transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * Sensitivity);
        //transform.LookAt(Target.transform.position);
        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * Sensitivity);
        if (moveBox != null)
        {
            if (!moveBox.bounds.Contains(transform.position) && Distance > MinDistance && rotationY > 0)
            {
                transform.position = moveBox.ClosestPoint(transform.position);
                targetPosition = transform.position;
                Distance -= 0.2f * Distance;

            }
            if (!TargetBox.bounds.Contains(Target.transform.position))
            {
                Target.transform.position = TargetBox.ClosestPoint(Target.transform.position);
                TargetObjPos = TargetBox.ClosestPoint(Target.transform.position);
            }
        }
        Debug.DrawLine(this.transform.position, this.transform.right * 100, Color.red);

    }
    private Vector3 TargetObjPos;
    private void OnEnable()
    {

        rotationX = this.transform.eulerAngles.y;
        rotationY = this.transform.eulerAngles.x;
    }
    private void OnDisable()
    {

    }
    bool isEnLarge(Vector2 oldP1, Vector2 oldP2, Vector2 newP1, Vector2 newP2)
    {
        //计算旧两点间的距离与新两点间的距离
        float oldLength = Mathf.Sqrt((oldP1.x - oldP2.x) * (oldP1.x - oldP2.x) + (oldP1.y - oldP2.y) * (oldP1.y - oldP2.y));
        float newLength = Mathf.Sqrt((newP1.x - newP2.x) * (newP1.x - newP2.x) + (newP1.y - newP2.y) * (newP1.y - newP2.y));

        //判断旧两点间的距离与新两点间的距离大小,如果旧的距离小于新的距离,说明是放大手势
        if (oldLength < newLength)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

 
    public void Move(Vector3 direction)
    {
        if (rotationY == 90)
        {
            return;
        }
        Vector3 right = transform.right;
        right.y = 0;
        right.Normalize();
        Vector3 up = transform.up;
        //up.y = 0;
        up.Normalize();
        Vector3 moveDirection = right * direction.x + up * direction.y;
        TargetObjPos = TargetObjPos + moveDirection;
        targetPosition = targetPosition + moveDirection;
    }
}

2、WASD控制相机移动,鼠标控制相机旋转

    public class CameraMoveAndRotate : MonoBehaviour
    {
        public GameObject target;
        public float sensitivity = 2f;
        public float speed = 0.1f;
        public bool IsClamp;
        /// <summary>
        /// 相机可移动区域 (限制围绕中心点和相机的 x ,z)
        /// </summary>
        public Bounds aroundPosBounds = new Bounds();

        // Start is called before the first frame update
        void Start()
        {
            if (target==null)
            {
                target = Camera.main.gameObject;
            }
        }
        旋转速度
        //public float rotationSpeed = 5f;
        上下旋转角度限制
        //public float maxVerticalAngle = 90f;
        //public float minVerticalAngle = -90f;
        旋转缓冲速度
        //public float lerpSpeed = 10f;
        //private float targetRotationX = 0f;
        //private float targetRotationY = 0f;

        // Update is called once per frame
        void Update()
        {
            Move();

            if (Input.GetMouseButton(1))
            {
                Rotate();
                //if (Input.GetMouseButton(1))
                //{
                //    // 获取鼠标输入的旋转增量
                //    float rotationXInput = -Input.GetAxis("Mouse Y");
                //    float rotationYInput = Input.GetAxis("Mouse X");
                //    // 根据旋转速度进行摄像机的旋转
                //    targetRotationX += rotationXInput * rotationSpeed;
                //    targetRotationY += rotationYInput * rotationSpeed;
                //    // 对上下旋转角度进行限制
                //    targetRotationX = Mathf.Clamp(targetRotationX, minVerticalAngle, maxVerticalAngle);
                //    // 根据旋转角度更新摄像机的欧拉角,Quaternion.Lerp可以使摄像机旋转更加平滑
                //    Quaternion targetRotation = Quaternion.Euler(targetRotationX, targetRotationY, 0f);
                //    transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, lerpSpeed * Time.deltaTime);
                //}

            }
            if (IsClamp)
            {
                moveInput = ClampVector3(target.transform.position, aroundPosBounds.min, aroundPosBounds.max);
                target.transform.position = moveInput;
            }
          
        }

        public Vector3 ClampVector3(Vector3 v, Vector3 min, Vector3 max)
        {
            v.x = Mathf.Clamp(v.x, min.x, max.x);
            v.y = Mathf.Clamp(v.y, min.y, max.y);
            v.z = Mathf.Clamp(v.z, min.z, max.z);
            return v;
        }


        private Vector3 moveInput;
        private void Move()
        {
            if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
            {
                transform.Translate(Vector3.forward * Time.deltaTime * speed);
            }

            if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
            {
                transform.Translate(Vector3.back * Time.deltaTime * speed);
            }

            if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
            {
                transform.Translate(Vector3.left * Time.deltaTime * speed);
            }

            if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
            {
                transform.Translate(Vector3.right * Time.deltaTime * speed);
            }

            if (Input.GetKey(KeyCode.E))
            {
                transform.Translate(Vector3.up * Time.deltaTime * speed);
            }

            if (Input.GetKey(KeyCode.Q))
            {
                transform.Translate(Vector3.down * Time.deltaTime * speed);
            }

            /*Vector3 vertMove = transform.forward * Input.GetAxis("Vertical");
            Vector3 horiMove = transform.right * Input.GetAxis("Horizontal");
            moveInput = vertMove + horiMove;
            moveInput.Normalize();
            transform.Translate(moveInput * Time.deltaTime * speed);*/
        }

        private void Rotate()
        {
            Vector2 mouseInput = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")) * sensitivity;
            transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y + mouseInput.x, transform.rotation.eulerAngles.z); //水平方向旋转
            transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles + new Vector3(-mouseInput.y, 0f, 0f));//摄像头垂直旋转
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值