Search code examples
c#unity-game-enginegame-physics

Move spawn object to random position


I have a spawner object. Every time a gameobject is spawned, I want that object to move randomly (wandering). The problem in my script is that the gameobject movement is very random (jittery). How can I solve this?

void Start ()
{
    InvokeRepeating("SpawnNPC", Spawntime, Spawntime);
}

// Update is called once per frame
void Update () {
    population = GameObject.FindGameObjectsWithTag("NPCobject");
    for (int i = 0; i < population.Length; i++)
    {
        getNewPosition();
        if (population[i].transform.position != pos)
        {
            population[i].transform.position = Vector3.MoveTowards(population[i].transform.position, pos, .1f);
        }
    }
}
void getNewPosition()
{
    float x = Random.Range(-22, 22);
    float z= Random.Range(-22, 22);

    pos = new Vector3(x, 0, z);
}

I made the New randomize vector in different method, because I plan to change it with pathfinder function and make it in different thread/task.


Solution

  • The source of the jitteriness comes from the fact that you are updating the position to move every frame so your objects never have a consistent location to move to. I would instead suggest attaching a new script to each of your objects that individually handles their movement. In that script you could do something like the following, which has a delay to keep the target position for more than 1 frame.

    float delaytimer;
    Vector3 pos;
    
    void Start () {
        getNewPosition(); // get initial targetpos
    }
    
    void Update () {
        delaytimer += Time.deltaTime;
    
        if (delaytimer > 1) // time to wait 
        {
            getNewPosition(); //get new position every 1 second
            delaytimer = 0f; // reset timer
        }
        transform.position = Vector3.MoveTowards(transform.position, pos, .1f);
    }
    
    void getNewPosition()
    {
        float x = Random.Range(-22, 22);
        float z= Random.Range(-22, 22);
    
        pos = new Vector3(x, 0, z);
    }