Unity: как перестать читать первое касание при использовании TouchPhase.Moved - PullRequest
0 голосов
/ 30 ноября 2018

У меня есть два сценария, один из которых является контроллером игрока:

void Update () {
   if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {


        Touch touch = Input.GetTouch(0);
        Ray ray = cam.ScreenPointToRay(touch.position);
        RaycastHit hit;

        if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
        {
            return;
        }


        if (Physics.Raycast(ray, out hit, 100))
        {

            Interactable interactable = hit.collider.GetComponent<Interactable>();
             if (interactable != null)
             {
                SetFocus(interactable);
             }
             else
             {
                motor.MoveToPoint(hit.point);

                RemoveFocus();
            }

        }
    }
}       

Тогда сценарий моей камеры:

void Update()
{
    currentZoom -= Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
    currentZoom = Mathf.Clamp(currentZoom, minZoom, maxZoom);

    currentYaw -= Input.GetAxis("Horizontal") * yawSpeed * Time.deltaTime;
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        Vector2 touchDirection = Input.GetTouch(0).deltaPosition;
        if (touchDirection.x > minSwipe || touchDirection.x < -minSwipe)
        {
            currentYaw -= touchDirection.x * yawSpeed / mobileYawReduction * Time.deltaTime;
        }

    }
}

// Update is called once per frame
void LateUpdate () {
    transform.position = target.position - offset * currentZoom;
    transform.LookAt(target.position + Vector3.up * pitch);

    transform.RotateAround(target.position, Vector3.up, currentYaw);
}

Оба эти варианта работают нормально: я могу двигать своего персонажас одним касанием и вращением камеры при смахивании, единственная проблема заключается в том, что когда я поворачиваю камеру, она регистрирует начало касания и начинает двигаться.как бы мне этого избежать?

1 Ответ

0 голосов
/ 30 ноября 2018

Вместо того, чтобы двигаться, когда начинается касание, вы можете двигаться только тогда, когда касание заканчивается, а положение касания не сильно изменилось во время касания.

Если касание и изменение позиции превышают небольшой порог, вместо этого интерпретируйте его как свайп и пропустите вызов целевого кодового блока, когда касание закончится.

// if movement was greater than interpret as swipe 
public float swipeThreshold = 0.01;

Vector2 startPosition ;
float movedDistance;

Touch touch;

void Update () 
{
    if (Input.touchCount <= 0) return;

    switch(Input.GetTouch(0).phase)
    {
        case TouchPhase.Began:
            // On begin only save the start position

            touch = Input.GetTouch(0);

            if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
            {
                return;
            }

            startPosition = touch.position;
            movedDistance = 0;
            break;

        case TouchPhase.Moved:
            // if moving check how far you moved

            movedDistance = Vector2.Distance(touch.position, startPosition );
            break;

        case TouchPhase.Ended:
            // on end of touch (like button up) check the distance
            // if you swiped -> moved more than swipeThreshold
            // do nothing

            if(movedDistance > swipeThreshold) break;

            Ray ray = cam.ScreenPointToRay(touch.position);
            RaycastHit hit;
            if (!Physics.Raycast(ray, out hit, 100)) break;

            Interactable interactable = hit.collider.GetComponent<Interactable>();
            if (interactable != null)
            {
                SetFocus(interactable);
            }
            else
            {
                motor.MoveToPoint(hit.point);
                RemoveFocus();
            }
            break;

        default:
            break;
    }
}

I, чем добавить тот же порогчтобы сценарий камеры был последовательным.Либо разделите это пороговое значение между ними (или даже получите его из другого скрипта), либо просто введите то же значение

public float swipeThreshold = 0.01;

Vector2 startPosition;

void Update()
{
    currentZoom -= Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
    currentZoom = Mathf.Clamp(currentZoom, minZoom, maxZoom);

    currentYaw -= Input.GetAxis("Horizontal") * yawSpeed * Time.deltaTime;

    if (Input.touchCount <= 0) return;

    switch(Input.GetTouch(0).phase)
    {
        case TouchPhase.Began:
            startPosition = Input.GetTouch(0).position;
            break;

        case TouchPhase.Moved:
            // if yet not moved enough do nothing
            var movedDistance = Vector2.Distance(Input.GetTouch(0).position, startPosition);
            if (movedDistance <= swipeThreshold) break;

            Vector2 touchDirection = Input.GetTouch(0).deltaPosition;
            if (touchDirection.x > minSwipe || touchDirection.x < -minSwipe)
            {
                currentYaw -= touchDirection.x * yawSpeed / mobileYawReduction * Time.deltaTime;
            }
            break;

        default:
            break;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...