Обнаружение пролистывания без потери немедленного отклика - PullRequest
0 голосов
/ 18 января 2019

Я создаю игру для Android с Unity. Есть только три способа управления движением персонажа:

  • Нажмите в правой половине экрана: перейти вправо
  • Нажмите в левой половине экрана: перейти влево
  • Проведите пальцем вверх: персонаж бросается вперед

Теоретически я знаю, что могу различать прикосновения с помощью TouchPhases (началось, переместилось, остановилось и закончилось). Когда я только обнаруживал касания, не заботясь о пролистываниях, я просто проверял, началась ли фаза касания, и заставлял игрока прыгать. Это чувствовалось быстро на моем устройстве.

Однако, поскольку я должен учитывать, что может произойти удар, я не могу инициировать действие прыжка, пока не обнаружу ThouchPhase.Ended. Это приводит к очень медленному реагирующему персонажу, который не прыгает, пока пользователь не поднимает палец на экране.

Я попытался использовать ThouchPhase.Moved и ThouchPhase.Stationary вместо этого, чтобы имитировать немедленный ответ, но мое решение довольно плохо с точки зрения определения разницы между касанием и пролистыванием:

Vector2 startTouchPosition;
Vector2 endTouchPosition;
Vector2 currentSwipe;

void Update()
{
    if (Input.touches.Length > 0)
    {
        for (int i = 0; i < Input.touchCount; i++)
        {
            Touch touch = Input.GetTouch(i);

            if (touch.phase == TouchPhase.Began)
            {
                //save began touch 2d point
                startTouchPosition = new Vector2(touch.position.x, touch.position.y);
            }

            if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
            {
                //save ended touch 2d point
                endTouchPosition = new Vector2(touch.position.x, touch.position.y);

                if (endTouchPosition.y - startTouchPosition.y < 5)
                {
                    if (touch.position.x > (Screen.width / 2))
                    {
                        JumpToRight();
                    }
                    else if (touch.position.x < (Screen.width / 2))
                    {
                        JumpToLeft();
                    }
                }
                else
                {
                    //create vector from the two points
                    currentSwipe = new Vector2(endTouchPosition.x - startTouchPosition.x, endTouchPosition.y - startTouchPosition.y);

                    //normalize the 2d vector
                    currentSwipe.Normalize();

                    //swipe upwards
                    if (currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
                    {
                        DashForward();
                    }
                }
            }
        }
    }
}

1 Ответ

0 голосов
/ 21 января 2019

Вот код, который я использовал. Я проверял, и это работает, но иногда я заметил задержку. Дайте мне знать, если это достаточно хорошо для вас. В основном вам не нужно проходить все касания, если вам не нужно мультитач. И вам просто нужны фазы начала и окончания.

using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;

public class touch : MonoBehaviour {
private Vector2 startTouchPosition;
private Vector2 endTouchPosition;
private Vector2 currentSwipe;
public Text textbox;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.touches.Length > 0)
    {

        Touch touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Began)
        {
            //save began touch 2d point
            startTouchPosition = new Vector2(touch.position.x, touch.position.y);
        }

        if (touch.phase == TouchPhase.Ended)
        {
            //save ended touch 2d point
            endTouchPosition = new Vector2(touch.position.x, touch.position.y);
            //create vector from the two points
            currentSwipe = new Vector2(endTouchPosition.x - startTouchPosition.x, endTouchPosition.y - startTouchPosition.y);

                //normalize the 2d vector
            currentSwipe.Normalize();
            if(Mathf.Abs(currentSwipe.y) < 0.1f && Mathf.Abs(currentSwipe.x) < 0.1f)
            {
                if (touch.position.x > (Screen.width / 2))
                {
                    textbox.text= "jump right";
                }
                else if (touch.position.x < (Screen.width / 2))
                {
                    textbox.text= "jump left";

                }
            }
            if (currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
            {
                textbox.text= "Dash forward";

            }
        }
    }
  }
}
...