Печать координатных точек в файл в Unity - PullRequest
0 голосов
/ 18 декабря 2018

В этом проекте существует случайно перемещающийся объект, координаты которого я должен распечатать в файл.Для этого я создал функцию с именем PrintPoints ().Однако я не знаю, где вызывать PrintPoints (), так как если бы я вызывал его в методе Update (), он выдает длинный и нелепый вывод, который, как я считаю, происходит потому, что Update () выполняется для каждого кадра.Мне просто нужно запустить Update () и распечатать координаты после того, как объект закончил движение (самый конец программы).

Как мне этого добиться?

Большое спасибо!

PS: ниже мой код

public class PlayerController : MonoBehaviour {

bool hasArrived;
private float movementDuration = 2.0f;
private float waitBeforeMoving = 2.0f;
private Vector3[] v = new Vector3[20];

//StreamWriter file = new StreamWriter("output.txt",true);
void Update()
{
    if (!hasArrived)
    {
        hasArrived = true;
        StartCoroutine(MoveToPoints());
    }
}

private IEnumerator MoveToPoints()
{


    for (int i = 0; i < v.Length; i++)
    {
        float timer = 0.0f;
        Vector3 startPos = transform.position;
        float x = RandomNum(timer);
        float y = RandomNum(x);
        float z = RandomNum(y);
        v[i] = new Vector3(x, y, z);

        while (timer < movementDuration)
        {
            timer += Time.deltaTime;
            float t = timer / movementDuration;
            t = t * t * t * (t * (6f * t - 15f) + 10f);
            transform.position = Vector3.Lerp(startPos, v[i], t);
            yield return null;
        }
        yield return new WaitForSeconds(waitBeforeMoving);
    }
}

void PrintPoints()
{
    //path of file
    string path = Application.dataPath + "/Player.txt";
    //create file if nonexistent
    if(!File.Exists(path))
    {
        File.WriteAllText(path, "The player blob visited these random coordinates: \n\n");
    }

    foreach(Vector3 vector in v)
    {
        File.AppendAllText(path, "(" + vector.x + ", " + vector.y + ", " + vector.z + ")\n\n");
    }


}

float RandomNum(float lastRandNum)
{
    //Random value range can be changed in the future if necessary
    float randNum = Random.Range(-10.0f, 10.0f);
    return System.Math.Abs(randNum - lastRandNum) < double.Epsilon ? RandomNum(randNum) : randNum;
}

}

Ответы [ 3 ]

0 голосов
/ 18 декабря 2018

Update () запускает каждый кадр, как вы сказали.Если вы хотите, чтобы метод MoveToPoints () вызывался только один раз, вы можете вызвать его в методе Start ().Если вы это сделаете, то можете вызвать метод PrintPoints () после вызова метода MoveToPoints ().

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

public class PlayerController : MonoBehaviour {

    private float movementDuration = 2.0f;
    private float waitBeforeMoving = 2.0f;
    private Vector3[] v = new Vector3[20];

    //StreamWriter file = new StreamWriter("output.txt",true);
    void Start()
    {
        this.MoveToPoints();
        this.PrintPoints();
    }

    private void MoveToPoints()
    {
        for (int i = 0; i < v.Length; i++)
        {
            float timer = 0.0f;
            Vector3 startPos = transform.position;
            float x = this.RandomNum(timer);
            float y = this.RandomNum(x);
            float z = this.RandomNum(y);
            v[i] = new Vector3(x, y, z);

            while (timer < movementDuration)
            {
                timer += Time.deltaTime;
                float t = timer / movementDuration;
                t = t * t * t * (t * (6f * t - 15f) + 10f);
                transform.position = Vector3.Lerp(startPos, v[i], t);
                yield return null;
            }
        }
    }

    void PrintPoints()
    {
        //path of file
        string path = Application.dataPath + "/Player.txt";
        //create file if nonexistent
        if(!File.Exists(path))
        {
            File.WriteAllText(path, "The player blob visited these random coordinates: \n\n");
        }

        foreach(Vector3 vector in v)
        {
            File.AppendAllText(path, "(" + vector.x + ", " + vector.y + ", " + vector.z + ")\n\n");
        }


    }

    float RandomNum(float lastRandNum)
    {
        //Random value range can be changed in the future if necessary
        float randNum = Random.Range(-10.0f, 10.0f);
        return System.Math.Abs(randNum - lastRandNum) < double.Epsilon ? RandomNum(randNum) : randNum;
    }
}
0 голосов
/ 18 декабря 2018
public class PlayerController : MonoBehaviour
{

    float movementDuration = 2.0f;
    WaitForSeconds waitBeforeMoving = new WaitForSeconds( 2f );
    Vector3[] path = new Vector3[20];

    void Start ()
    {
        StartCoroutine( MainRoutine() );
    }

    IEnumerator MainRoutine ()
    {
        //generate new path:
        for( int i=0 ; i<path.Length ; i++ )
        {
            float timer = 0.0f;
            Vector3 startPos = transform.position;
            float x = RandomNum( timer );
            float y = RandomNum( x );
            float z = RandomNum( y );
            path[i] = new Vector3(x, y, z);
        }

        //traverse path:
        for( int i=0 ; i<path.Length ; i++ )
        {
            float timer = 0.0f;
            Vector3 startPos = transform.position;
            while( timer<movementDuration )
            {
                timer += Time.deltaTime;
                float t = timer / movementDuration;
                t = t * t * t * (t * (6f * t - 15f) + 10f);
                transform.position = Vector3.Lerp( startPos , path[i] , t );
                yield return null;
            }
            yield return waitBeforeMoving;
        }

        //print path:
        PrintPoints();
    }

    void PrintPoints ()
    {
        string filepath = Application.dataPath + "/Player.txt";
        if( File.Exists( filepath )==false )
        {
            File.WriteAllText( filepath , "The player blob visited these random coordinates: \n\n" );
        }
        foreach( Vector3 vector in path )
        {
            File.AppendAllText( filepath , $"{ JsonUtility.ToJson(vector) }\n\n" );
        }
    }

    float RandomNum ( float lastRandNum )
    {
        //Random value range can be changed in the future if necessary
        float randNum = Random.Range(-10.0f, 10.0f);
        return System.Math.Abs(randNum - lastRandNum) < float.Epsilon ? RandomNum(randNum) : randNum;
    }

}
0 голосов
/ 18 декабря 2018

В этой программе вы должны вызывать PrintPoints () один раз, после вызова MoveToPoints (), потому что вы печатаете все точки в векторе.Лучший способ - вы печатаете только одну точку при вызове PrintPoints.Я бы дал Point для печати в качестве аргумента метода, например:

void PrintPoint(Vector3 vector)
{
   //path of file
  string path = Application.dataPath + "/Player.txt";
  //create file if nonexistent
  if(!File.Exists(path))
  {
    File.WriteAllText(path, "The player blob visited these random coordinates: \n\n");
  }

  File.AppendAllText(path, "(" + vector.x + ", " + vector.y + ", " + vector.z + ")\n\n");
}
...