android 上的统一触摸操作

unity touch actions on android

我想检测用户何时点击了某个对象,以及用户手指何时仍停留在屏幕上,以检查手指在哪个对象上结束。 在点击事件上它会像这样平滑:

void OnMouseEnter()
{
    // this is where the finger hovered on
}

void OnMouseDown()
{
    // this is the first touch
}

void OnMouseUp()
{
    // this is where the finger was released from the screen
}

所以,基本上我喜欢 OnMouseEnter()

谢谢

您可以使用 Camera.main.ScreenPointToRay() 将您的触摸动作位置投射到光线中,然后使用 Raycast 查看是否它击中了一个物体。例如:

void Update () {
    for (int i = 0; i < Input.touchCount; ++i) {
        if (Input.GetTouch (i).phase == TouchPhase.Began) {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position);
            if (Physics.Raycast (ray, out hit, 1000f)) {
                Debug.Log("Touch enter on " + hit.collider.name);
            }
        }
    }
}

如果您不考虑多点触控,您也可以使用鼠标输入操作。为移动平台构建时,触摸操作将转换为鼠标操作。

void Update () {
    if (Input.GetMouseButtonDown (0)) {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        if (Physics.Raycast (ray, out hit, 1000f)) {
            Debug.Log("Touch enter on " + hit.collider.name);
        }
    }
}

不过,我想最后即使你想使用第一个版本(这样它可以处理多点触控),你也会想要实现第二个版本。仅仅是因为这样您就可以在编辑器上用鼠标模拟触摸。

void Update () {
#if UNITY_EDITOR
        if (Input.GetMouseButtonDown (0)) {
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
#else
        for (int i = 0; i < Input.touchCount; ++i) {
            if (Input.GetTouch (i).phase == TouchPhase.Began) {
                Ray ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position);
#endif
                RaycastHit hit;
                if (Physics.Raycast (ray, out hit, 1000f)) {
                    Debug.Log("Touch enter on " + hit.collider.name);
                }
#if !UNITY_EDITOR
            }
#endif
        }
    }

虽然有点乱,但是像这样的东西应该可以解决问题。

这些示例应该适用于您的 OnMouseEnter() 案例。使用相同的想法,您可以实现其他响应(悬停和 release/exit)。