Unity C # Mobile Control Проведите влево и вправо - PullRequest
0 голосов
/ 14 января 2019

Я сделал 3d-игру с Unity и C #. Я не знаю, как сделать управление объектом (игроком) влево и вправо, проведя пальцем по экрану мобильного телефона.

Это мой код C #:

    using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;

    public float forwardForce = 300f;
    public float sidewaysForce = 200f;

    // Update is called once per frame
    void FixedUpdate()
    {
      rb.AddForce(0, 0, forwardForce * Time.deltaTime);

      if (Input.GetAxis("Horizontal") > 0.1)
      {
        rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0);
      }

      if (Input.GetAxis("Horizontal") < -0.1)
      {
        rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0);
      }
    }
}

1 Ответ

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

Вы должны ознакомиться с Руководствами по мобильному касанию , Руководством по мобильному касанию и Input.GetTouch . Короче говоря: вы должны получить касание, сохранить начальную позицию и сравнить ее с текущими позициями.

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;

    public float forwardForce = 300f;
    public float sidewaysForce = 200f;

    private Vector2 initialPosition;    

    // Update is called once per frame
    void Update()
    {
        // are you sure that you want to become faster and faster?
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);

        if(Input.touchCount == 1)
        {
            touch = Input.GetTouch(0);

            if(touch.phase == TouchPhase.Began)
            {
                initialPosition = touch.position;
            } 
            else if(touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
            {
                // get the moved direction compared to the initial touch position
                var direction = touch.position - initialPosition;

                // get the signed x direction
                // if(direction.x >= 0) 1 else -1
                var signedDirection = Mathf.Sign(direction.x);

                // are you sure you want to become faster over time?
                rb.AddForce(sidewaysForce * signedDirection * Time.deltaTime, 0, 0);
            }
        }
    }
}

Примечание: это всегда сравнивается с начальной позицией касания => вы не идете в другом направлении, пока вы не

  1. Переместить касание в исходное положение в другом направлении
  2. И поскольку вы используете AddForce, ждите столько же времени, сколько вы добавили в другом направлении

Возможно, вам лучше сравнивать только предыдущую позицию касания, а не исходную:

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;

    public float forwardForce = 300f;
    public float sidewaysForce = 200f;

    private Vector2 lastPosition;    

    // Update is called once per frame
    void Update()
    {
        // are you sure that you want to become faster and faster?
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);

        if(Input.touchCount == 1)
        {
            touch = Input.GetTouch(0);

            if(touch.phase == TouchPhase.Began)
            {
                lastPosition = touch.position;
            }
            if(touch.phase == TouchPhase.Moved)
            {
                // get the moved direction compared to the initial touch position
                var direction = touch.position - lastPosition ;

                // get the signed x direction
                // if(direction.x >= 0) 1 else -1
                var signedDirection = Mathf.Sign(direction.x);

                // are you sure you want to become faster over time?
                rb.AddForce(sidewaysForce * signedDirection * Time.deltaTime, 0, 0);

                lastPosition = touch.position;
            }
        }
    }
}

Теперь вам все равно придется провести столько же времени ... оно не учитывает пройденное расстояние. Так что, возможно, вместо этого вы должны использовать это:

// get the moved direction compared to the initial touch position
var direction = touch.position - lastPosition ;

// are you sure you want to become faster over time?
rb.AddForce(sidewaysForce * direction.x * Time.deltaTime, 0, 0);

так что чем больше вы проводите, тем больше силы добавляется.

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