首页 > 解决方案 > 如何统一从游戏中心获得(0,0)

问题描述

我是 Unity 的新手,我正在尝试使用Input.touch[0]. 我正在触摸该点,并使用它来计算滑动增量,但问题是输入坐标来自屏幕的左角。我需要屏幕中心的 0,0。这是我的脚本:

    public class SwipeController : MonoBehaviour
    {
    private bool tap, swipeLeft, swipeRight, swipeUp, swipeDown;
    private bool isDragging;
    private Vector2 startTouch, swipeDelta;

    private void Update()
        {
        tap = swipeLeft = swipeRight = swipeUp = swipeDown = false;

    //stand Alone Inputs

    if (Input.GetMouseButtonDown(0))
    {
        isDragging = true;
        tap = true;
        startTouch = Input.mousePosition;
    } else if (Input.GetMouseButtonUp(0)) {
        isDragging = false;
        Reset();
    }


    //MOBILE INPUTS

    if (Input.touches.Length > 0 )
    {
        if(Input.touches[0].phase == TouchPhase.Began)
        {
            tap = true;
            isDragging = true;
            startTouch = Input.touches[0].position;
        } else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
        {
            isDragging = false;
            Reset();
        }
    }

    //Distance calcs

    if (isDragging)
    {
        if(Input.touches.Length > 0)
        {
            swipeDelta = Input.touches[0].position - startTouch;
        } else if (Input.GetMouseButton(0)) {
            swipeDelta = (Vector2)Input.mousePosition - startTouch;
        }

        //DEAD ZONE?

    if (swipeDelta.magnitude > 100)
        {
            float x = swipeDelta.x;
            float y = swipeDelta.y;

            if (Mathf.Abs(x) > Mathf.Abs(y))
            {
                //left or right
                if (x < 0)
                {
                    swipeLeft = true;
                } else
                {
                    swipeRight = true;
                }
            } else
            {
                // top or bottom
                if (y < 0 )
                {
                    swipeDown = true;
                } else
                {
                    swipeUp = true;
                }
            }

            Reset();
        }
    }
}

    private void Reset()
    {
       startTouch = swipeDelta = Vector2.zero;
    }

    public Vector2 SwipeDelta { get { return swipeDelta; } }
    public bool SwipeLeft { get { return swipeLeft; } }
    public bool SwipeRight { get { return swipeRight; } }
    public bool SwipeUp { get { return swipeUp; } }
    public bool SwipeDown { get { return swipeDown; } }
    }

我错过了什么?

标签: c#unity3d

解决方案


您正在寻找 Camera.ScreenToWorldPoint。

触摸输入以像素而非世界单位记录。如果将触摸位置输入到相机的ScreenToWorldPoint方法中,返回的 Vector3 就是被触摸的世界位置。通常用户只会使用:

Vector3 point = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y));

但建议缓存 Camera.main 引用以提高性能。上面链接的官方文档就是一个很好的例子。


推荐阅读