unity中在触控屏中Input.GetAxis("Mouse X")判断出现失误

在pc端中可以通过Input.GetAxis(“Mouse X”)或Input.GetAxis(“Mouse Y”)判断鼠标移动的方向,

但在触控屏中,以Input.GetAxis(“Mouse X”)或Input.GetAxis(“Mouse Y”)判断单点触控的手指滑动的方向容易发生错误,故不建议在触控屏中使用此方法。

参照:https://blog.csdn.net/poda_/article/details/51334051

以下是在触控屏的单点触控或pc鼠标滑动控制物体旋转:

using UnityEngine;
public class ContralObject : MonoBehaviour {
    public GameObject MainBuilding; //主建筑模型
    private bool isPressLeft = false;//是否刚刚开始旋转
    private Vector2 newPosition;
    private Vector2 oldPosition;
     void Update()
    {
        
        //控制物体旋转
        if (Input.GetMouseButton(0))//鼠标左键
        {
            if (isPressLeft == false)
            {
                oldPosition = Input.mousePosition;
                isPressLeft = true;
                return;
            }
            else
            {
                newPosition = Input.mousePosition;
            }
            if (Mathf.Abs(newPosition.x - oldPosition.x) > Mathf.Abs(newPosition.y - oldPosition.y) && Mathf.Abs(newPosition.x - oldPosition.x) > 0.5f)
            {
            MainBuilding.transform.Rotate(Vector3.down * (newPosition.x - oldPosition.x) * Time.deltaTime * 5, Space.World);//绕Y轴进行旋转
            }
           /*
           //控制x轴,即上下角度旋转
            if (Mathf.Abs(newPosition.x - oldPosition.x) < Mathf.Abs(newPosition.y - oldPosition.y) && Mathf.Abs(newPosition.y - oldPosition.y) > 0.5f)
            {
                Vector3 add = MainBuilding.gameObject.transform.localEulerAngles + Vector3.right * (newPosition.y - oldPosition.y) * 0.1f;
                float xx = add.x;
                if (xx >= 66 && xx < 180)
                {
                    xx = 66;
                }
                if (xx < 0)
                {
                xx = 0;
                }
                MainBuilding.gameObject.transform.localEulerAngles = new Vector3(xx, MainBuilding.gameObject.transform.localEulerAngles.y, MainBuilding.gameObject.transform.localEulerAngles.z);
            }*/
            oldPosition = newPosition;
      }
      if (Input.GetMouseButtonUp(0))
        {
            isPressLeft = false;
        }
    }
}

你可能感兴趣的:(unity中在触控屏中Input.GetAxis("Mouse X")判断出现失误)