Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Jagged Movement

Discussion in 'Scripting' started by Tarik1989, Oct 6, 2019.

  1. Tarik1989

    Tarik1989

    Joined:
    Oct 6, 2019
    Posts:
    4
    Can anyone tell me why the below is printing all of the directions and giving my enemy jagged movement? Appreciate any advice.

    void CheckWandering()
    {

    if (isWalking)
    {
    anim.SetBool("isIdle", false);
    if (Random.Range(0,4) == 0)
    {
    print("right");
    transform.position += Vector3.right * moveSpeed * Time.fixedDeltaTime;

    }
    if (Random.Range(0, 4) == 1)
    {
    print("left");
    transform.position += Vector3.left * moveSpeed * Time.fixedDeltaTime;
    }
    if (Random.Range(0, 4) == 2)
    {
    print("up");
    transform.position += Vector3.up * moveSpeed * Time.fixedDeltaTime;
    }
    if (Random.Range(0, 4) == 3)
    {
    print("down");
    transform.position += Vector3.down * moveSpeed * Time.fixedDeltaTime;
    }

    }
    else
    {
    anim.SetBool("isIdle", true);
    }
    }
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    Hi and welcome!
    Please use code tags. It's explained the first sticky on this subforum. Makes stuff a lot more readable.

    Your main problem regarding your question is that you create a new random number in each if statement. So you are basically rolling a dice, saying "do XYZ if result is 1", then you roll a different other dice and ask again "do ABC only if result is 2" and so on. So technically, all if statements can be true, or none of them. Instead you'll want to save the result of Random.Range(0,4) in an int variable and compare that number to 0, 1, 2 or 3 instead.
     
    Tarik1989 likes this.
  3. Tarik1989

    Tarik1989

    Joined:
    Oct 6, 2019
    Posts:
    4
    Thank you for the reply and feedback. I managed to fix the problem and realise my error by watching a tutorial video but this explanation is very good. Sorry about the code block, new to the forum and coding!
     
  4. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    No problem, that's why i mentioned it. Keep having fun! :)