Skip to content

Combo ​

A character uses skills one at a time. When the last three were slash, slash and kick, each within a second of the one before, the next skill comes out in its ultimate form. The history keeps the skills, and the skillUsed handler checks it before choosing the state.

luau
const Canopy = require("@Canopy")

export type Skill = "slash" | "kick" | "burst"
export type Context = {
	history: Canopy.History<Name, Skill>,
}
export type Event = "skillUsed" | "skillEnded"
export type Name = "free" | "usingSkill" | "ultimate"

const COMBO: { Skill } = {
	"slash",
	"slash",
	"kick",
}
const MAX_GAP = 1

const S = Canopy.setup<<Context, Event, Name, Skill, Skill>>()

-- Whether the last skills are the combo, each started within MAX_GAP seconds of the one before.
const function isComboReady(history: Canopy.History<Name, Skill>): boolean
	if not history:endsWith(COMBO) then
		return false
	end

	const entries = history:getEntries(#COMBO)

	for index = 2, #entries do
		const gap = entries[index].enteredAt - entries[index - 1].enteredAt

		if gap > MAX_GAP then
			return false
		end
	end

	return true
end

const tree = S.tree({
	initial = "free",
	states = {
		free = S.state({
			on = {
				skillUsed = function(context, run, skill)
					if isComboReady(context.history) then
						context.history:clear()

						return S.goTo("ultimate", skill)
					end

					return S.goTo("usingSkill", skill)
				end,
			},
		}),
		usingSkill = S.state({
			record = function(context, run)
				const skill = run.data

				assert(skill, "usingSkill is entered with the skill used")

				return skill
			end,
			on = {
				skillEnded = "free",
			},
		}),
		ultimate = S.state({
			duration = 1.5,
			onTimeUp = "free",
		}),
	},
})

return {
	S = S,
	tree = tree,
}

ultimate has no record, so the ultimate form does not count towards the next combo, and the history is cleared when it starts.

luau
const ReplicatedStorage = game:GetService("ReplicatedStorage")

const SkillStates = require(ReplicatedStorage.SkillStates)

const S = SkillStates.S

const history = S.history({
	limit = 8,
})
const machine = S.new(SkillStates.tree, {
	history = history,
}, {
	at = os.clock(),
	history = history,
})

machine:send("skillUsed", "slash", os.clock())
-- ...the skill ends...
machine:send("skillEnded", nil, os.clock())

A skill pressed while the last one is still running finds no handler in usingSkill, so it is lost. To keep a fast player's combo, send skills with a buffer: the press waits until skillEnded moves the machine back to free, then free takes it.

luau
machine:send("skillUsed", "kick", os.clock(), {
	buffer = 0.3,
})