Движение игрока Unity 2D - PullRequest
       19

Движение игрока Unity 2D

0 голосов
/ 10 апреля 2020

У меня было мое движение единства, работающее на моем компьютере, однако, когда я пытаюсь играть на своем android, оно вообще не движется для меня. Я уверен, что это, вероятно, небольшая ошибка, которую я пропускаю, но я был бы очень признателен за любую помощь! Я не получаю никаких ошибок при попытке запустить мой код, если это поможет! Я предоставлю код ниже:

using UnityEngine;
using System.Collections;

//Adding this allows us to access members of the UI namespace including Text.
using UnityEngine.UI;

public class PlayerControler : MonoBehaviour {

    public Text countText;          //Store a reference to the UI Text component which will display the number of pickups collected.
    //public Text winText;          //Store a reference to the UI Text component which will display the 'You win' message.
    private double count;               //Integer to store the number of pickups collected so far.


    //Player movement controls
    private Vector3 touchPosition;  //where your finger touches screen
    private Vector3 direction;      //direction you drag sprite
    private Rigidbody2D rb2d;       //Store a reference to the Rigidbody2D component required to use 2D Physics.
    public float speed = 10f;               //Floating point variable to store the player's movement speed.


    // Use this for initialization
    void Start()
    {
        //Get and store a reference to the Rigidbody2D component so that we can access it.
        rb2d = GetComponent<Rigidbody2D> ();

        //Initialize count to zero.
        count = 0;

        //Initialze winText to a blank string since we haven't won yet at beginning.
        //winText.text = " "; //error here??

        //Call our SetCountText function which will update the text with the current value for count.
        //SetCountText ();
    }

    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
            touchPosition.z = 0;
            direction = (touchPosition - transform.position);
            rb2d.velocity = new Vector2(direction.x , direction.y) * speed;

            if(touch.phase == TouchPhase.Ended)
            {
                rb2d.velocity = Vector2.zero;
            }
        }
    }

    //OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
    void OnTriggerEnter2D(Collider2D other) 
    {
        //Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
        if (other.gameObject.CompareTag ("PickUp")) 
        {
            //... then set the other object we just collided with to inactive.
            other.gameObject.SetActive(false);

            //Add one to the current value of our count variable.
            count = count + 1;

            //Update the currently displayed count by calling the SetCountText function.
            //SetCountText ();
        }


    }

1 Ответ

0 голосов
/ 10 апреля 2020

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

rb2d.velocity = new Vector2(direction.x , direction.y) * speed * Time.deltaTime;

Убедитесь, что скрипт присоединен к игровому объекту с помощью компонента Rigidbody2D. Кроме того, если ваш компьютер не поддерживает сенсорный ввод, вы можете использовать ввод с помощью мыши для получения одинакового результата на компьютере и мобильном устройстве.

    if (Input.GetMouseButtonUp(0))
    {
        rb2d.velocity = Vector2.zero;
    }
    else if (Input.GetMouseButton(0))
    {
        touchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        touchPosition.z = 0;
        direction = (touchPosition - transform.position);
        rb2d.velocity = new Vector2(direction.x, direction.y) * speed * Time.deltaTime;
    }

Этот код также работает на мобильных устройствах.

...