I have a JavaScript canvas game setup using Phaser framework. When I first made my character able to run, jump, and crouch, I used lots of if/else conditions and ended up with an ugly, buggy mess. I have read some articles about finite state machines and that seems to be the solution I need.
I am using javascript-state-machine and can't work out what kind of logic belongs where. My old logic looked something like this:
function update() { // ticks every frame
if (cursors.right.isDown && !jumping && !crouching) {
runRight(); // set character velocity and animation
} else if( // more absurd complexity
}
What should be my first thought when trying to add a movement to the character? Do I think about the input first or define a state on the state machine first?
What exactly is a state? You can be moving right and jumping, but also moving to the right and not jumping. How are those movements described in terms of states?
What checks the user input for keys that are pressed or released and how does that interact with the changing of states?
A very helpful answer would include a psuedo code example of running and jumping that uses javascript-state-machine
. I've read this interesting article that addresses character movement with an FSM, but I'm unable to apply those principles in JavaScript, with Phaser, and with this FSM library.
Here's some code from my most recent refactoring attempt in case it helps. I doubt it's even on the right track.
hero.sm = StateMachine.create({
initial: 'standing',
events: [
{name: 'move', from: ['standing', 'jumping'], to: 'running'},
{name: 'jump', from: ['standing', 'running'], to: 'jumping'},
{name: 'stop', from: ['running', 'jumping'], to: 'standing'},
],
callbacks: {
// onEVENT
onmove: (event, to, from, direction) => {
},
// onSTATE
onrunning: () => {
},
// onSTATEleave
onrunningleave: () => {
}
}
})
hero.update = () => {
if (cursors.right.isDown || cursors.left.isDown) {
hero.sm.move(cursors.right.isDown ? 'right' : 'left');
} else {
hero.sm.stop();
}
}