- Home /
Best practice for programmatic character animation
Hey all,
I'm having a bit of an architecture dilemma. I'm trying to decide how I should control the animation of my little robot character. Here's the scenario:
user selects a tile for the robot to move to
if the robot is not facing the right direction, rotate the body in the right direction
move the robot to the destination tile
Where I'm having trouble is in sequencing the animations. Should I use a Coroutine to animate the rotation and then once complete start the move Coroutine? Or should I set up a state machine and just check if the robot is in the right state on update (Idle, Rotating, Moving)?
I feel like the state machine is probably the more traditional way to do it, but I wanted to get some other opinions.
Cheers
Answer by Bunny83 · Jul 15, 2011 at 02:57 AM
Well, if the task is not interruptable a coroutine would work fine. If you want to be able to stop the process at any time a state machine would be better ;). A coroutine is really useful when you have a quite linear command chain.
IEnumerator MoveToTile(Vector3 target)
{
//Start looping rotation animation here
while(not facing the the target)
{
//Rotate
yield return null;
}
//switch to run / walk animation
while(not reached target)
{
//Move forward
yield return null;
}
//stop the animation / switch to idle...
}
Just in case you didn't know: coroutines are also statemachines but the state-handling is hidden. The compiler even creates a whole seperate desicated nested class for each coroutine. Since the state-stuff is not accessible, coroutines are not as flexible as own statemachines ;)
This worked great for me and made total sense for my specific problem. Cheers!!
Answer by Waz · Jul 15, 2011 at 03:01 AM
I'd say that every Update event, the robot should calculate afresh whether it needs to turn or move forward. So a modeless solution. Only if that choice was expensive to make would I use a modal approach. The trouble with the modal approach is that you then need more code to kick it out of the mode (eg. when player chooses new tile before robot reaches first choice).
Your answer
![](https://koobas.hobune.stream/wayback/20220612144001im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Detecting last frame of animation, without StateMachineBehaviours or Animation Events 0 Answers
Why does Unity animator makes calling children's SetActive fail? 0 Answers
Animation Curve or Coroutine? Performance question. 1 Answer
Coroutine / Switch case 1 Answer
Easier way of creating transitions in the animator? 1 Answer