Getting started
Canopy is a hierarchical state machine. You build a tree of states once, then make one machine per owner from it.
In development
Canopy is in early development. Its API may still change.
Install
Canopy is one package, on Ember, pesde, and Wally.
embr add idemandsky/canopypesde add idemandsky/canopy[dependencies]
Canopy = "idemandsky/canopy@0.1.0"Require the library
const Canopy = require("@Canopy")Name your types
Call setup once per kind of machine, with its types between << and >>: the context every state can read, the events the machine can be sent, the names of its states, the data events carry, and what the history records. Pass nil for the last two when you don't use them. Everything built with S is then checked against these types.
const Canopy = require("@Canopy")
export type Context = { health: number }
export type Event = "knockedBack" | "landed"
export type Name = "free" | "knockedBack" | "flying" | "groundImpact"
const S = Canopy.setup<<Context, Event, Name, nil, nil>>()Build a tree
A tree lists the outermost states and the one to start in. A state with children names its own initial child.
const tree = S.tree({
initial = "free",
states = {
free = S.state({
on = {
knockedBack = "knockedBack",
},
}),
knockedBack = S.state({
initial = "flying",
on = {
knockedBack = "knockedBack",
},
states = {
flying = S.state({
on = {
landed = "groundImpact",
},
}),
groundImpact = S.state({
duration = 0.8,
onTimeUp = "free",
}),
},
}),
},
})
return {
S = S,
tree = tree,
}knockedBack handles being knocked back again for both of its children, so neither flying nor groundImpact needs its own handler.
Make a machine
Make one machine per owner with S.new, and call process with the current time, for example each frame. A machine reads no clock itself.
const ReplicatedStorage = game:GetService("ReplicatedStorage")
const RunService = game:GetService("RunService")
const CharacterStates = require(ReplicatedStorage.CharacterStates)
const S = CharacterStates.S
const machine = S.new(CharacterStates.tree, {
health = 100,
}, {
at = os.clock(),
})
machine:send("knockedBack") -- free > knockedBack > flying
machine:send("landed") -- knockedBack > groundImpact
RunService.Heartbeat:Connect(function()
machine:process(os.clock()) -- back to free once 0.8 seconds have passed
end)