Скрипт случайного движения вызывает зависание Unity - PullRequest
0 голосов
/ 03 ноября 2019

У меня есть сетка, состоящая из 16 плиток. Теперь в основном я хочу, чтобы пользователь нашел путь к конечному местоположению, перемещаясь случайным образом по вариантам, которые он имеет в сетке.

На данный момент мне удалось создать функции для перемещения на шаг вверх, вниз, влевои правильно. Проблема возникает, когда я пытаюсь кодировать в случайном порядке. В идеале это настроено так, что он не может выходить за пределы сетки.

Вот что я получил:

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


public class Move : MonoBehaviour

{
    void Up()
    {
        //get the Input from Horizontal axis
        float horizontalInput = Input.GetAxis("Horizontal");
        //get the Input from Vertical axis
        float verticalInput = Input.GetAxis("Vertical");

        //update the position
        transform.position = transform.position + new Vector3(0, 1.5f, 0);

        //output to log the position change
        Debug.Log(transform.position);
    }

    void Down()
    {
        //get the Input from Horizontal axis
        float horizontalInput = Input.GetAxis("Horizontal");
        //get the Input from Vertical axis
        float verticalInput = Input.GetAxis("Vertical");

        //update the position
        transform.position = transform.position + new Vector3(0, -1.5f, 0);

        //output to log the position change
        Debug.Log(transform.position);
    }

    void Left()
    {
        //get the Input from Horizontal axis
        float horizontalInput = Input.GetAxis("Horizontal");
        //get the Input from Vertical axis
        float verticalInput = Input.GetAxis("Vertical");

        //update the position
        transform.position = transform.position + new Vector3(-1.5f, 0, 0);

        //output to log the position change
        Debug.Log(transform.position);
    }

    void Right()
    {
        //get the Input from Horizontal axis
        float horizontalInput = Input.GetAxis("Horizontal");
        //get the Input from Vertical axis
        float verticalInput = Input.GetAxis("Vertical");

        //update the position
        transform.position = transform.position + new Vector3(1.5f, 0, 0);

        //output to log the position change
        Debug.Log(transform.position);
    }



    void Start()
    {
        var finalLocation = new Vector3(-0.5f, 0.5f, 0);
        var currentLocation = transform.position;

        while (currentLocation != finalLocation)
        {
            int randomNum = Random.Range(0, 3);

            if (randomNum == 0)
            {
                Up();
            }
            else if (randomNum == 1)
            {
                Down();
            }
            else if (randomNum == 2)
            {
                Left();
            }
            else if (randomNum == 3)
            {
                Right();
            }

        }
    }
}

ОБНОВЛЕННЫЙ КОД РАБОТЫ:

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


public class Move : MonoBehaviour

{
    void Up()
    {
        //update the position
        transform.position = transform.position + new Vector3(0, 1.5f, 0);

        //output to log the position change
        Debug.Log(transform.position);
    }

    void Down()
    {
        //update the position
        transform.position = transform.position + new Vector3(0, -1.5f, 0);

        //output to log the position change
        Debug.Log(transform.position);
    }

    void Left()
    {
        //update the position
        transform.position = transform.position + new Vector3(-1.5f, 0, 0);

        //output to log the position change
        Debug.Log(transform.position);
    }

    void Right()
    {
        //update the position
        transform.position = transform.position + new Vector3(1.5f, 0, 0);

        //output to log the position change
        Debug.Log(transform.position);
    }



    void Update()
    {
        var finalLocation = new Vector3(2.5f, 2.0f, -2.0f);
        var currentLocation = transform.position; 
        int randomNum = Random.Range(0, 4);

        if (currentLocation != finalLocation) { 
                if (randomNum == 0)
            {
                Up();
            }
            else if (randomNum == 1)
            {
                Down();
            }
            else if (randomNum == 2)
            {
                Left();
            }
            else if (randomNum == 3)
            {
                Right();
            }
            return;
        }
    }
}

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

Ответы [ 2 ]

1 голос
/ 03 ноября 2019

Вот некоторые проблемы:

  • horizontalInput и verticalInput никогда не используются внутри ваших функций

  • while(currentLocation != finalLocation) Это условиеможет потерпеть неудачу в некоторых ситуациях. Unity использует float для координат, это означает, что он должен быть точно в той же позиции, каждое десятичное место должно быть одинаковым.

  • Random.Range(0, 3) вернетсяслучайное число от 0 (включительно) до 3 (исключая), поэтому единственными возможными значениями будут 0, 1 и 2. Сценарий никогда не вызовет функцию Right().

Unity использует один поток для запуска ваших сценариев по умолчанию, если вы поместите цикл while для перемещения объекта в какое-либо место, он заморозит всю игру, пока объект не окажется в нужном месте. Я рекомендую вам использовать функцию Update(), она вызывается каждый кадр.

1 голос
/ 03 ноября 2019

Несколько проблем:

  1. Ваш объект застрял в бесконечном цикле while, потому что ему не разрешено выходить (и делать такие вещи, как рендеринг кадра, получение ввода от пользователя и т. Д. ), пока ваш сценарий случайного перемещения не достигнет finalLocation. Вы не даете игре время делать что-либо еще.
    Вы почти наверняка хотите, чтобы это была сопрограмма или Update функция.
  2. Random.Range возвращает целое число в диапазоне от min (включительно) до max (исключая), поэтому ваш вызов к нему никогда не вернется 3.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...