Skip to content

Instantly share code, notes, and snippets.

@iammerrick
Created July 25, 2019 06:24
Show Gist options
  • Save iammerrick/afb54b7b9903e7b960a65a653f376583 to your computer and use it in GitHub Desktop.
Save iammerrick/afb54b7b9903e7b960a65a653f376583 to your computer and use it in GitHub Desktop.
Coordinate character states with state machines allowing for async transitions.
const app = new PIXI.Application({ transparent: true });
const { Machine, interpret, send, sendParent, assign } = window.XState;
document.body.appendChild(app.view);
// Invoked child machine
const CharacterMachine = a => {
return Machine({
id: "Kolohe",
initial: "active",
context: {
app: a
},
states: {
active: {
invoke: {
id: "activate",
src: context => {
const kolohe = PIXI.Sprite.from(
"examples/assets/bunny.png"
);
kolohe.anchor.set(0.5);
kolohe.x = context.app.screen.width / 2;
kolohe.y = context.app.screen.height / 2;
context.app.stage.addChild(kolohe);
return new Promise(resolve => {
TweenLite.to(kolohe, 2, {
x: 100,
onComplete: () => {
resolve({
kolohe
});
}
});
});
},
onDone: {
target: "resting",
actions: assign({
kolohe: (context, event) => event.data.kolohe
})
}
}
},
resting: {
invoke: {
id: "resting",
src: context => callback => {
return new Promise(resolve => {
TweenLite.to(context.kolohe, 2, {
y: 100,
onComplete: () => {
resolve();
}
});
});
},
onDone: {
target: "finished"
}
}
},
finished: { type: "final" }
}
});
};
const parentMachine = Machine({
id: "parent",
initial: "pending",
states: {
pending: {
invoke: {
src: CharacterMachine(app),
// Kolohe is done!
onDone: "timesUp"
}
},
timesUp: {
type: "final"
}
}
});
const service = interpret(parentMachine)
.onTransition(state => console.log(state.value))
.start();
@iammerrick
Copy link
Author

ScreenFlow

@iammerrick
Copy link
Author

This is really weird because if characters self mount and unmount based on states... They're almost like mini components.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment