Simple GML state machine for GameMaker 2.3+
stateMachine = new DTG_StateMachine();state = new DTG_State();
// create a state named "start"
stateMachine.add("start",state);Code to run when the state machines enters the state: This is called automatically.
state.onEnter = function(obj)
{
// code here
// obj references the State() instance
}Code to run when the state machines exits the state: This is called automatically
state.onExit = function(obj)
{
// code here
// obj references the State() instance
}This needs to be added to your step event for the onStep events to fire:
stateMachine.step()Code to run each step:
state.onStep = function(obj)
{
// code here
// obj references the State() instance
}This needs to be added to yuour draw event for the onDraw events to fire:
stateMachine.draw()Code to run each draw event:
state.onDraw = function(obj)
{
// code here
// obj references the State() instance
}Note: onStep and onDraw are not actually tied to the Gamemaker step or draw events. You can run them in the beginXXXX/endXXXX events.
If you want to use "getFrames()" call, you must call stateMachine.step() in a step event.
You can also make custom events
state.addCustom("my_custom_eventname", function(obj) {
// code here
// obj references the State() instance
});Execute that code later:
stateMachine.custom("my_custom_eventname");The state machine needs to be in that state in order for this to work.
Each state can save a struct as user data
Adding user data to the current state:
foo = {
bar: "spam"
};
stateMachine.addUserData(foo);Retrieving user data from the current state:
userData = stateMachine.getUserData();userData would then contain the data from the foo struct. This is a copy, not a reference, so it will be independent of the original struct.
You can get the amount of time that has passed since the current state has been running.
timeInMicroseconds = stateMachine.getTime(false);
timeInSeconds = stateMachine.getTime(true);Also the number of frames since the state started.
frames = stateMachine.getFrames()