如何在统一中从游戏中心获得 (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; } }
}

我错过了什么?

您正在寻找 Camera.ScreenToWorldPoint。

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

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

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