Enemy AI
An enemy idles until it spots a target, then fights: it chases until it is close, and attacks until it has swung three times. A hit stuns it for one to two seconds, unless it is chasing, when the hit only staggers it. Every enemy shares one tree and has its own machine, and one group processes them all.
const Canopy = require("@Canopy")
export type Context = {
model: Model,
target: Model?,
}
export type Event = "spotted" | "lost" | "hit"
export type Name = "idle" | "fighting" | "chasing" | "attacking" | "stunned"
const ATTACK_RANGE = 6
const S = Canopy.setup<<Context, Event, Name, Model, nil>>()
const function distanceTo(context: Context): number
const target = context.target
if not target then
return math.huge
end
return (context.model:GetPivot().Position - target:GetPivot().Position).Magnitude
end
const tree = S.tree({
initial = "idle",
states = {
idle = S.state({
on = {
spotted = function(context, run, target)
context.target = target
return S.goTo("fighting")
end,
},
}),
fighting = S.state({
initial = "chasing",
on = {
lost = "idle",
hit = "stunned",
},
onEnd = function(context)
context.target = nil
end,
states = {
chasing = S.state({
onProcess = function(context)
return if distanceTo(context) <= ATTACK_RANGE then S.goTo("attacking") else nil
end,
on = {
-- A hit while chasing only staggers it: the hit stops here, so `fighting` does not stun it.
hit = function(context)
context.model:SetAttribute("Staggered", true)
return S.stay()
end,
},
}),
attacking = S.withMemory(function()
return {
swings = 0,
nextSwingAt = 0,
}
end):state({
onProcess = function(context, run, now)
if distanceTo(context) > ATTACK_RANGE then
return S.goTo("chasing")
end
if now < run.memory.nextSwingAt then
return nil
end
run.memory.swings += 1
run.memory.nextSwingAt = now + 0.6
return if run.memory.swings >= 3 then S.goTo("chasing") else nil
end,
}),
},
}),
stunned = S.state({
duration = {
1,
2,
},
onTimeUp = "idle",
}),
},
})
return {
S = S,
tree = tree,
}attacking counts its swings in its own memory, so each time it is entered the count starts at zero again, with no reset code. fighting clears the target when the enemy leaves it, whether it lost the target or was stunned. A hit reaches chasing first: it returns S.stay(), so the hit is taken there and fighting never stuns a chasing enemy.
Add every enemy to one group, and pass one seeded Random so the stun lengths can be replayed. An enemy standing idle costs the group nothing per frame; only the enemies with onProcess or a duration that ended run:
const RunService = game:GetService("RunService")
const ServerStorage = game:GetService("ServerStorage")
const EnemyStates = require(ServerStorage.EnemyStates)
const S = EnemyStates.S
const random = Random.new(42)
const enemies = S.group()
const function spawnEnemy(model: Model)
const machine = S.new(EnemyStates.tree, {
model = model,
target = nil,
}, {
at = os.clock(),
random = random,
-- Keeps the last 20 events, to read with getTrace when an enemy acts strangely.
trace = 20,
})
enemies:add(machine)
model.Destroying:Once(function()
machine:stop()
end)
end
RunService.Heartbeat:Connect(function()
enemies:process(os.clock())
end)