- Home /
2D Grid Movement - StartCoroutine, IEnumerator, SmoothMovement best practices?
Unity: 5 Type: 2D Axes: x,y
My question, I think, is dealing with StartCoroutine and moving on a grid. The roguelike tutorial seems like a good example, but as soon I setup my own grid size behavior becomes different. I also have a question related to the roguelike tutorial and how it appears that StartCoroutine is called twice to move.
[Edit] Movement is turn based. Player moves, then enemies are cycled for movement.
Roguelike Tutorial - Calls StartCoroutine Twice?
The tutorial has a method AttemptMove. The flow to StartCoroutine is AttemptMove > Move > StartCoroutine(SmoothMovement(end)). After calling that method it then calls move again. Would this cause strange behavior on the moving GameObject?
protected override void AttemptMove <T> (int xDir, int yDir)
{
food--;
foodText.text = "Food: " + food;
//This results in a StartCoroutine by calling Move
base.AttemptMove <T> (xDir,yDir);
RaycastHit2D hit;
//This also results in a StartCoroutine
if (Move (xDir, yDir, out hit))
{
SoundManager.instance.RandomizeSfx(moveSound1,moveSound2);
}
CheckIfGameOver();
GameManager.instance.playersTurn = false;
}
Best Practice?
My issue with trying to snap a moving unit to the grid appears to have been fixed by preventing any more user input until the StartCoroutine has finished. I added a isMoving bool to the class that handles movement. If the object is already moving new input is ignored.
My GameObject has a Rigidbody2D and is is kinematic (basically pulled from the tutorial). If I do not prevent user input during that coroutine my object moves off the grid fairly quickly and begins to slop around as input appears to be running across multiple coroutines. I take it that the movement coroutine is starting with a position off the grid during the movement animation.
Is a flag to prevent further input the correct way to address that behavior or is that just a hack to work around something I don't understand in Unity. I am new to Unity and C#.
GridMove is another 2D grid movement example. It also uses a flag to prevent further input until the coroutine is finished.