0
\$\begingroup\$

I'm trying to create a periodic timer in Unity, so that I can create a GameObject that randomly moves around. Unfortunately, with my current code, the GameObject goes in a constant direction and doesn't ever update to change the direction. I believe that it might not be changing because the coroutine might only be called once, but I'm not exactly sure how to create a timer that can do this. I've been searching for a while online, but I haven't found anything yet. Here's the main code that has been causing the issue:

   public float speed;
   public float wanderDegrees;

    void Update() 
    {

        if (gameObject.name == "Enemy_R")
        {
            StartCoroutine("RandomMovements");
        }
    }

    IEnumerator RandomMovements()
    {
            float angle = Mathf.PerlinNoise(-wanderDegrees, wanderDegrees) * Mathf.Deg2Rad;
            Vector2 direction = new Vector2(Mathf.Sin(angle), -Mathf.Cos(angle));
            yield return new WaitForSeconds(1f);
            Vector2 velocity = direction * speed;
            transform.Translate(velocity * Time.deltaTime);
    }
\$\endgroup\$
4
\$\begingroup\$
public float speed = 1f;
public float wanderDegrees = 45f;

Vector2 _velocity;

void Start() {
    // Don't check the game object's name here. Just put this component
    // on ONLY the enemy that's supposed to use it, and not on the others.
    // if (gameObject.name == "Enemy_R")

    // Don't look up your coroutine by its name - that's unnecessarily slow.
    StartCoroutine(ChooseRandomDirectionsPeriodically());
}

// You want to move every frame, not just when you pick a new direction, 
// so put that in Update.
void Update() {
    transform.Translate(_velocity * Time.deltaTime);
}

IEnumerator ChooseRandomDirectionsPeriodically()
{
    // Use a while loop to repeat this behaviour over and over again at intervals.
    while (true) {
        // The way you were using noise here was nonsensical. 
        // Let's use a random die roll instead.
        float angle = Random.Range(-wanderDegrees, wanderDegrees) * Mathf.Deg2Rad;
        Vector2 direction = new Vector2(Mathf.Sin(angle), -Mathf.Cos(angle));
        // Cache the velocity in a member variable to be used in Update.
        _velocity = direction * speed;

        // Wait at the end of the loop, after we've done all our work.
        yield return new WaitForSeconds(1f);
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.