Skip to content

State Machine Behaviours

Wyatt Gillette edited this page Jan 12, 2022 · 9 revisions

A State Machine Behaviour is a special class of script. You can attach a StateMachineBehaviour script to an individual state within a state machine. This allows you to write code that will execute when the state machine enters, exits or remains within a particular state. This means you do not have to write your own logic to test for and detect changes in state.

A few examples for the use of this feature might be to:

  • Play sounds as states are entered or exited
  • Perform certain tests (eg, ground detection) only when in appropriate states
  • Activate and control special effects associated with specific states

State Machine Behaviours can be created and added to states in a very simple way.

Spatial myModel = ...;

// Get AnimComposer from your model
AnimComposer composer = myModel.getControl(AnimComposer.class);

// Create the controller and the parameters
AnimatorController animator = new AnimatorController(composer);
animator.addParameter("distance", AnimatorControllerParameterType.Float);
myModel.addControl(animator);

// Define states for animations.
AnimatorStateMachine sm = animator.getLayer(0).getStateMachine();

AnimatorState patrol = sm.addState("Patrol", AnimDefs.WalkWithRifle);
patrol.addStateMachineBehaviour(new PatrolState());

AnimatorState chase = sm.addState("Chase", AnimDefs.RifleRun);
chase.addStateMachineBehaviour(new ChaseState());

AnimatorState attack = sm.addState("Attack", AnimDefs.FiringRifleAuto);
attack.addStateMachineBehaviour(new AttackState());

// Define the transitions and conditions for each state
AnimatorStateTransition patrolToChase = patrol.addTransition(chase);
patrolToChase.addCondition(AnimatorConditionMode.Less, 12f, "distance");

AnimatorStateTransition chaseToPatrol = chase.addTransition(patrol);
chaseToPatrol.addCondition(AnimatorConditionMode.Greater, 12f, "distance");

AnimatorStateTransition chaseToAttack = chase.addTransition(attack);
chaseToAttack.addCondition(AnimatorConditionMode.Less, 5f, "distance");

AnimatorStateTransition attackToChase = attack.addTransition(chase);
attackToChase.addCondition(AnimatorConditionMode.Greater, 6f, "distance");

// set the initial state.
sm.setDefaultState(patrol);
public class PatrolState implements StateMachineBehaviour {

    @Override
    public void onStateEnter(AnimatorController animator) {
        //do something...
    }

    @Override
    public void onStateUpdate(AnimatorController animator, float tpf) {
        //do something...
    }

    @Override
    public void onStateExit(AnimatorController animator) {
        //do something...
    }

}
Clone this wiki locally