M
M
Mikhail Karimov2020-12-05 23:45:35
Unity
Mikhail Karimov, 2020-12-05 23:45:35

How to choose a random side of the enemy's movement once by x in unity2d?

It is necessary that the enemy chooses a random value of movement once (to the right or to the left), but when using Random.Range in FixedUpdate , he starts to constantly choose the direction (which is logical), but how can I do the definition of the side once ?

private void FixedUpdate()
    {
        if (EnemyFindaPlayer == false)
        {
            float direction = player.transform.position.x - transform.position.x;

            if (Mathf.Abs(direction) < 20)
            {
                Vector3 pos = transform.position;
                pos.x += Mathf.Sign(direction) * speedMoveClassical * Time.deltaTime;
                transform.position = pos;
            }




            if (speedMoveClassical == 0)
            {
                anim.SetBool("isRunning", false);
            }
            else
            {
                anim.SetBool("isRunning", true);
            }

            if (facingRight == false && direction > 0)
            {
                Flip();
            }
            else if (facingRight == true && direction < 0)
            {
                Flip();
            }
        }
        else
        {

            Invoke("FreeMove" , MomementMoveDelay);


            if (speedMoveClassical == 0)
            {
                anim.SetBool("isRunning", false);
            }
            else
            {
                anim.SetBool("isRunning", true);
            }

            if (facingRight == false && speedMoveClassical > 0)
            {
                Flip();
            }
            else if (facingRight == true && speedMoveClassical < 0)
            {
                Flip();
            }


        }
    }

   private void FreeMove()
    {
        rb.velocity = new Vector2( Random.Range(-speedMoveClassical, speedMoveClassical), 0);

    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question