Sunday, December 25, 2016

animation - How to transition between states and mix states in a finite state machine?


I don't understand how to use a finite state machine with the entity controlled by the player.


For example I have a Mario style game (2d platform). I can jump, run, walk, take damage, swim, etc. So my first thought was to use this actions as states. But what happens, if you are running when you take damage? Or jumping, taking damage and shooting at the same time?


I just want to add functionalities (actions) to the player in a clean way (not using it for all the actions in the entity update) .



Answer



I guess the normal way is to have multiple state machines. This way you can stick to atomic states which often makes your live a lot easier than having to deal with complex states.



For example:



  • Damage Mode: Normal, Invulnerable (as in just hit), invincible (as in got a star)

  • Pace: Walking Mode, Running Mode

  • Abilities: Normal, Super, Fire, Fly

  • Movement Type: Walking, Swimming, Flying


In object oriented designed there is the sate pattern for this. It boils down to having one interface per state machine. And a class per possible state which implements this interface.


To give an example: There would be an interface DamageMode and subclasses NormalDamageMode, InvulnerableDamageMode and InvincibleDamageMode. Whenever the player collidates with an enemy the method DamageMode.collision(enemy) is called. It is handled by the class responsible for the current state.


So if damageMode == NormalDamageMode the player will be damaged and the state variable will be set to InvulnerableDamageMode. In InvulnerableDamageMode nothing happens and in InvincibleDamageMode the enemy will be damaged. Of course there needs to be timers to go back from InvulnerableDamageMode and InvincibleDamageMode to NormalDamageMode.



The main advantage of the state pattern compared to if-elseif-elseif-elseif-blocks is that it allows to structure your code better.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...