У меня есть работающий скрипт детектора, но я не знаю, как подключить его к контроллеру персонажа. - PullRequest
0 голосов
/ 12 марта 2020

Моя игра - бесконечный раннер, и персонаж должен двигаться только вдоль оси Y. Я хочу, чтобы игрок двигался вверх или вниз в зависимости от удара, и я подумал, что мог бы сделать это, заявив, что если игрок активирует onSwipeUp или down, то они будут двигаться в этом направлении, но я не смог заставить его работать.

Это сценарий контроллера плеера до того, как я попытался внедрить в него элементы управления смахиванием:

public class Player : MonoBehaviour
{

private Vector2 targetPos;

public float yIncrement;
public float maxHeight;
public float minHeight; 

private void Update()
    {

    transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);

    if (Input.GetKeyDown(KeyCode.W) && transform.position.y < maxHeight)
    {
        Instantiate(effect, transform.position, Quaternion.identity);
        targetPos = new Vector2(transform.position.x, transform.position.y + yIncrement);
    }
    else if (Input.GetKeyDown(KeyCode.S) && transform.position.y > minHeight)
    {
        Instantiate(effect, transform.position, Quaternion.identity);
        targetPos = new Vector2(transform.position.x, transform.position.y - yIncrement);
    }
}

А это сценарий обнаружения смахивания:

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

public class SwipeTest : MonoBehaviour
{
    private Vector2 fingerDown;
    private Vector2 fingerUp;
    public bool detectSwipeOnlyAfterRelease = false;
public float SWIPE_THRESHOLD = 20f;

// Update is called once per frame
void Update()
{

    foreach (Touch touch in Input.touches)
    {
        if (touch.phase == TouchPhase.Began)
        {
            fingerUp = touch.position;
            fingerDown = touch.position;
        }

        //Detects Swipe while finger is still moving
        if (touch.phase == TouchPhase.Moved)
        {
            if (!detectSwipeOnlyAfterRelease)
            {
                fingerDown = touch.position;
                checkSwipe();
            }
        }

        //Detects swipe after finger is released
        if (touch.phase == TouchPhase.Ended)
        {
            fingerDown = touch.position;
            checkSwipe();
        }
    }
}

void checkSwipe()
{
    //Check if Vertical swipe
    if (verticalMove() > SWIPE_THRESHOLD && verticalMove() > horizontalValMove())
    {
        //Debug.Log("Vertical");
        if (fingerDown.y - fingerUp.y > 0)//up swipe
        {
            OnSwipeUp();
        }
        else if (fingerDown.y - fingerUp.y < 0)//Down swipe
        {
            OnSwipeDown();
        }
        fingerUp = fingerDown;
    }

    //Check if Horizontal swipe
    else if (horizontalValMove() > SWIPE_THRESHOLD && horizontalValMove() > verticalMove())
    {
        //Debug.Log("Horizontal");
        if (fingerDown.x - fingerUp.x > 0)//Right swipe
        {
            OnSwipeRight();
        }
        else if (fingerDown.x - fingerUp.x < 0)//Left swipe
        {
            OnSwipeLeft();
        }
        fingerUp = fingerDown;
    }

    //No Movement at-all
    else
    {
        //Debug.Log("No Swipe!");
    }
}

float verticalMove()
{
    return Mathf.Abs(fingerDown.y - fingerUp.y);
}

float horizontalValMove()
{
    return Mathf.Abs(fingerDown.x - fingerUp.x);
}

//////////////////////////////////CALLBACK FUNCTIONS/////////////////////////////


 public void OnSwipeUp()
    {
        Debug.Log("Swipe UP");
    }

   public void OnSwipeDown()
    {
        Debug.Log("Swipe Down");
    }

    void OnSwipeLeft()
    {
        Debug.Log("Swipe Left");
    }

    void OnSwipeRight()
    {
        Debug.Log("Swipe Right");
    }
}

1 Ответ

0 голосов
/ 12 марта 2020

Вы можете установить логическое значение c для каждого направления прокрутки. В первых строках обновления установите для этих логических значений значение false, в функциях onswipe установите для соответствующих логических значений значение true. Затем обратитесь к сценарию swipetest из сценария проигрывателя и проверьте, установлено ли для логического значения swipe значение true.

Код будет выглядеть примерно так:

player:

public class Player : MonoBehaviour
{

private Vector2 targetPos;

public float yIncrement;
public float maxHeight;
public float minHeight; 

public SwipeTest swipetest;

private void OnEnable()
{
  swipetest = (SwipeTest)FindObjectOfType(typeof(SwipeTest));
}

private void Update()
    {

    transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);

    if (swipetest.swipeUp && transform.position.y < maxHeight)
    {
        Instantiate(effect, transform.position, Quaternion.identity);
        targetPos = new Vector2(transform.position.x, transform.position.y + yIncrement);
    }
    else if (swipetest.swipeDown && transform.position.y > minHeight)
    {
        Instantiate(effect, transform.position, Quaternion.identity);
        targetPos = new Vector2(transform.position.x, transform.position.y - yIncrement);
    }
}

swipetest

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

public class SwipeTest : MonoBehaviour
{
    private Vector2 fingerDown;
    private Vector2 fingerUp;
    public bool detectSwipeOnlyAfterRelease = false;
public float SWIPE_THRESHOLD = 20f;

public bool swipeUp = false;
public bool swipeDown = false;
public bool swipeLeft = false;
public bool swipeRight = false;


// Update is called once per frame
void Update()
{

  swipeUp = false;
  swipeDown = false;
  swipeLeft = false;
  swipeRight = false;

    foreach (Touch touch in Input.touches)
    {
        if (touch.phase == TouchPhase.Began)
        {
            fingerUp = touch.position;
            fingerDown = touch.position;
        }

        //Detects Swipe while finger is still moving
        if (touch.phase == TouchPhase.Moved)
        {
            if (!detectSwipeOnlyAfterRelease)
            {
                fingerDown = touch.position;
                checkSwipe();
            }
        }

        //Detects swipe after finger is released
        if (touch.phase == TouchPhase.Ended)
        {
            fingerDown = touch.position;
            checkSwipe();
        }
    }
}

void checkSwipe()
{
    //Check if Vertical swipe
    if (verticalMove() > SWIPE_THRESHOLD && verticalMove() > horizontalValMove())
    {
        //Debug.Log("Vertical");
        if (fingerDown.y - fingerUp.y > 0)//up swipe
        {
            OnSwipeUp();
        }
        else if (fingerDown.y - fingerUp.y < 0)//Down swipe
        {
            OnSwipeDown();
        }
        fingerUp = fingerDown;
    }

    //Check if Horizontal swipe
    else if (horizontalValMove() > SWIPE_THRESHOLD && horizontalValMove() > verticalMove())
    {
        //Debug.Log("Horizontal");
        if (fingerDown.x - fingerUp.x > 0)//Right swipe
        {
            OnSwipeRight();
        }
        else if (fingerDown.x - fingerUp.x < 0)//Left swipe
        {
            OnSwipeLeft();
        }
        fingerUp = fingerDown;
    }

    //No Movement at-all
    else
    {
        //Debug.Log("No Swipe!");
    }
}

float verticalMove()
{
    return Mathf.Abs(fingerDown.y - fingerUp.y);
}

float horizontalValMove()
{
    return Mathf.Abs(fingerDown.x - fingerUp.x);
}

//////////////////////////////////CALLBACK FUNCTIONS/////////////////////////////


 public void OnSwipeUp()
    {
      swipeUp = true;
    }

   public void OnSwipeDown()
    {
      swipeDown = true;
    }

    void OnSwipeLeft()
    {
      swipeLeft = true;
    }

    void OnSwipeRight()
    {
      swipeRight = true;
    }
}
...