Search Unity

Move 2D gameobject to another one smoothly?

Discussion in '2D' started by NotVeryGoodAtThs, Oct 24, 2021.

  1. NotVeryGoodAtThs

    NotVeryGoodAtThs

    Joined:
    May 3, 2021
    Posts:
    8
    I'm trying to recreate the same effect that Among Us has in its main menu, where the crewmates move across the screen seemingly randomly. I'm trying to make my game object move to a random object in the array called nodes. However, after doing this, the guy moves very quickly, and increasing the movementTime variable crashes Unity. Anyone able to give me a suggestion?
    Code (CSharp):
    1.     private void Update()
    2.     {
    3.         if (!moving)
    4.         {
    5.             moving = true;
    6.             int timeToWait = Random.Range(0, 3);
    7.             StartCoroutine(Move());
    8.         }
    9.     }
    10.  
    11.     IEnumerator Move()
    12.     {
    13.         float movementTime = 5f;
    14.         float currentMovementTime = 0;
    15.         int endPoint = Random.Range(0, nodes.Length);
    16.         while (Vector2.Distance(transform.localPosition, nodes.ElementAt(endPoint).position) > 0)
    17.         {
    18.             currentMovementTime += Time.deltaTime;
    19.             transform.localPosition = Vector3.Lerp(transform.position, nodes.ElementAt(endPoint).position,
    20.                 currentMovementTime / movementTime);
    21.         }
    22.         moving = false;
    23.         yield return null;
    24.     }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,735
    You need to put a
    yield return null;
    somewhere within your while loop.

    Unity locks up until your code either returns or yields. Your entire while loop occurs while the game is frozen, all in one frame, because there is no yield inside of it.
     
  3. NotVeryGoodAtThs

    NotVeryGoodAtThs

    Joined:
    May 3, 2021
    Posts:
    8
    omg thank you sooo much! you made my school project come along so much better! thanks for the help, have a great day king
     
    Kurt-Dekker likes this.