Creature behaviour and AI

Everything a creature does comes from its species' AI: a function of the game that runs once per frame and decides where it walks, which animation it plays, when it notices the hunter and what it does then. Script mods can watch it, steer it, borrow from it or replace it, from small changes (raptors that bite instead of killing) to a completely new brain. Nothing changes unless a script asks: a game without mods plays exactly as the original.

This page goes from the lightest touch to the deepest:

  1. Events: react to what creatures and the hunter do.
  2. Reading a creature: what it knows, what it wants.
  3. Steering its own AI: mood, tame, fight targets, speed factors, armor.
  4. The game's creature functions: walk, sense, attack, jump, roar, die as the AIs do.
  5. Brains: another species' AI, a ready-made one, or your own Lua function.
  6. The AI toolkit: Ice Age's AI building blocks for any creature.

Every function, field and event is in the reference: the ai namespace, the Creature methods and fields on the world page, and the Events page. All of it is new in API 3: put "api": 3 into your mod.json.

Events

Event When Cancel
damage a creature takes damage from any source (source: hunter, creature, script); amount writable no damage
death a creature's death begins, whatever the cause: the frame after its health reached 0 (a per-frame check of c.alive can see a team wiped out before the last death event)
kill the killing blow (shots, fights, scripts); tranquilized
despawn / body_removed a living creature / a body leaves the world (reason: script, clear, ship, game)
creature_attack a creature attacks the hunter or another creature; damage writable for the hunter it misses
creature_hunt / creature_hunt_end it starts / stops chasing the hunter; cause (sight, smell, hearing, shot ...) it calms down
creature_flee / creature_flee_end it starts / stops running from him it calms down
notice it notices the hunter (sight, smell, hearing) it does not
equipment binoculars up / down, the map (radar) opens / closes it stays down / closed
request resupply, relocation, evacuation asked for nothing is asked
arrive the supply bag landed, picked up, relocated, evacuated
reload the weapon in hand reloads not now

The hunter's other events (shot, hit, weapon_change, call, player_damage, player_death) are on the Events page. hit now also fires for shots into a deadly spot (e.mortal), so a mod can block those kills too.

Non-lethal attacks. In the game a creature that reaches the hunter kills him. Give the bite a damage and it takes health instead; he dies when it is all he has left:

on("creature_attack", function(e)
  if e.hunter then
    e.damage = e.creature.predator and 35 or 15   -- health per bite (the hunter has 128)
  end
end)

Reading a creature

Field / method What it tells
c.mood "calm", "alert" (it knows about the hunter), "hunt" (it chases him), "flee" (it runs from him), "dead"
c.alerted, c.huntingPlayer the same as booleans
c:awareOfHunter() what told it: "sight", "smell", "hearing", "shot", "hurt", "near", "script" ...
c:threat() {predator, hunting, distance, heading, closing, eta, mood}: how dangerous it is right now
c.chaser, c.target, c.fightMode who hunts it, whom it hunts, its fight plan
c:sees(), c:smells(), c:senses(), c:hears(radius) the game's own sense tests for this creature, now
ai.state(c) the raw state number and fear time behind c.mood

Both games' AIs keep the same state: 0 calm, 1 alarmed (a predator hunts, a plant eater flees), 2 just noticed, 3 and 5 the T-Rex looking and roaring, plus a fear timer. c.mood turns that into words for every species: a creature hunts when its AI's way leads at the hunter, it flees when its way leads away from him.

Steering its own AI

Field Effect
c.mood = "calm" / "alert" / "hunt" / "flee" the safe way to set its AI's state: calm it, alarm it as a noise would, send it at the hunter, make it run
c.tame = true it ignores the hunter: never notices, hunts, flees or attacks him
c.target = other / c:attack(other) it goes after another creature with its own chase and bite, also while world.fights is off
c.moveSpeed, c.turnSpeed, c.animSpeed how fast its AI moves it, turns it, animates it (1 = the game's)
c.armor the share of every damage it takes (0.5 = half)
c.canKillHunter = false its attacks on the hunter miss
c.speed, c.sight, c.smell, c.hearing (API 1) its time factor and senses

Each of these belongs to one creature and goes with it (a new hunt, a reload of the scripts).

-- a slow, armoured, half-blind T-Rex that only charges when it hears you
on("spawn", function(e)
  local c = e.creature
  if c.species == "trex" then
    c.moveSpeed, c.armor, c.sight = 0.8, 0.5, 0.3
  end
end)

The game's creature functions

These do one frame of what the AIs do, for creatures whose AI you replaced (a brain, c.ai = false):

Method
c:walkTo(x, z [, opts]), c:runTo(x, z [, opts]) way finding around trees, rocks and water, turning, speeding up, terrain collision, the walk / run animation with sound; returns the distance left and whether it arrived
c:idle() stands, plays its calm idles
c:turnToward(x, z [, degreesPerSecond]) turns
c:wander([radius]), c:fleeFrom(x, z [, distance]) a new walk target as its AI picks one / away from a point
c:attackHunter() the game's attack when he is in reach (AddDeadBody: creature_attack, player_death)
c:attack(other), c:bite(other) a fight with its own AI / an instant scripted bite
c:hurt(amount [, opts]) a hit as from a shot: alarm, blood trail, death at 0
c:die([opts]) the death path: kill event, death animation, body, trophy for the hunter's kill
c:jump(), c:roar([face]) its leap / its roar with sound
c:nearby(radius [, filter]) creatures around it
c:stockAI([species]) one frame of its species' own AI (or another compatible one)

ai.anims(c) tells which animations a species has: walk, run, idle, kill (its attack), jump, roar, its idles and its speeds; it takes a creature or a species (an id, a type number or world.species(id)). Each game has its own species and numbers (the species tables on the world page).

Species whose AI never stands have no idles (Dinosaur Hunter's raptors and Allosaurus: ai.anims(c).idles is empty), so c:idle() holds a step. ai.setIdles(species, {anims}) names the ones c:idle() plays, often spare animations of the model; nil gives the species its AI's list again, and the scripts' lists are undone when they unload:

ai.setIdles("velociraptor", {2, 3, 7})   -- the Velociraptor's model has these three unused

Brains

c.brain replaces what runs in place of a creature's species AI. Around it the game still does everything else: the blood trail of a wounded creature, c.speed, fights, creature_after_ai. A dead creature always plays its own death.

c.brain = "velociraptor"   -- another species' AI (when the animations line up: ai.compatible)
c.brain = "prey"           -- Ice Age-style brains for any species: "prey", "predator", "defender"
c.brain = function(c, dt) ... end   -- your own
c.brain = nil              -- its own AI again
ai.setSpeciesBrain("trex", "prey")   -- every T-Rex grazes and flees

A complete Lua brain

A scavenger: it follows the hunter at a distance, freezes when he looks at it, runs when he comes close, and bites only from behind. Everything it does goes through the game's own functions.

local function behind(c)   -- is it behind the hunter? (his view looks along player.forward)
  local x, _, z = player.pos()
  local fx, fz = player.forward()
  return (c.x - x) * fx + (c.z - z) * fz < 0
end

local function scavenger(c, dt)
  local x, _, z = player.pos()
  local d = c:distanceTo(x, z)
  c.data.cool = (c.data.cool or 0) - dt
  if d < 1200 and not behind(c) then
    c:fleeFrom(x, z, 3000)
    c:runTo(c.targetX, c.targetZ)          -- too close and seen: run
  elseif d < 400 and behind(c) and c.data.cool <= 0 then
    if c:attackHunter() then c.data.cool = 3 end   -- a bite from behind (creature_attack decides the damage)
  elseif d > 3000 then
    c:walkTo(x, z, {arrive = 2500})        -- keep up
  elseif behind(c) then
    c:walkTo(x, z, {arrive = 350})         -- creep closer while he looks away
  else
    c:idle()                               -- freeze while he looks
  end
end

keys.bind("F6", function()
  local c = world.spawnNear(game.id() == "iceage" and "hyaenodon" or "troodon", 3000)
  if c then c.brain = scavenger end
end)
on("creature_attack", function(e) if e.hunter then e.damage = 20 end end)

Mixing brains

A brain can hand single frames to other brains: c:stockAI() (its own species' AI), ai.run(c, "prey"). Fights work through the species' AI, so a brain that sets a target lets the stock AI do the chasing:

c.brain = function(c, dt)
  if c.target then return c:stockAI() end      -- c:attack(...) set it: its own chase and bite
  local x, _, z = player.pos()
  c:walkTo(x, z, {arrive = 800})               -- else: follow the hunter
end

The Guard Pet example is built this way.

The AI toolkit

Ice Age builds its animal AIs from six helpers (AIGen_* in the game). The ai namespace has them for every creature of both games, so a Lua brain can be written exactly like an Ice Age AI. They share one AI frame per creature: call ai.begin(c) first each frame, then the helpers in this order. Speeds are the game's: units per millisecond, times the creature's scale.

-- the Ice Age wolf's AI, in Lua, for any species
local function wolf(c, dt)
  local A = ai.anims(c)
  local targetDist, hunterDist = ai.begin(c)
  local x, _, z = player.pos()
  if c.alerted and hunterDist < 11000 then
    c.targetX, c.targetZ = x, z                  -- hunting: its way leads at the hunter
    ai.eat(c)                                    -- his death when he is within reach of its mouth
  elseif not ai.exploreArea(c, 8048) then        -- calm: wander (a new target when it reached the old one)
    targetDist = ai.begin(c)
  end
  ai.selectWay(c, 2048, c.alerted, 1, 0.333)     -- heading to the target, around obstacles and water
  local looped = ai.animate(c)                   -- the animation clock
  local anim = c.anim
  if looped then
    anim = c.alerted and A.run or (math.random() < 0.97 and A.walk or (A.idles[1] or A.walk))
  end
  ai.phaseChanging(c, anim, anim == A.walk or anim == A.run)   -- the new animation with the game's blend and sound
  local left = ai.rotate(c, anim == A.walk or anim == A.run)
  local speed = anim == A.run and A.runSpeed / 1000 or anim == A.walk and A.walkSpeed / 1000 or 0
  if left > 90 then speed = speed * (2 - left / 90) end         -- turning on the spot first
  ai.thinkSpeed(c, speed, A.walk)                -- speed, movement with the terrain collision, tilt
end
Helper Ice Age's What it does
ai.begin(c) the start of every AI remembers its animation and time, measures the target and hunter distances
ai.animate(c) the blend and clock of its animation; true when it looped
ai.exploreArea(c, r) AIGen_ExploreArea wandering: a new walk target when it reached the old one
ai.selectWay(c, ...) AIGen_SelectWay its heading to the target, around obstacles (and water)
ai.phaseChanging(c, anim, blend) AIGen_PhaseChanging switches the animation with the blend and its sound
ai.rotate(c, ...) AIGen_RotationToTargetAlpha turns it toward the heading
ai.thinkSpeed(c, speed, ...) AIGen_ThinkSpeed speeds up / slows down, moves it with the terrain collision, tilts it
ai.eat(c, ...) AIGen_Eat kills the hunter within reach of its mouth
ai.lookForAWay, ai.moveCharacter, ai.tilt, ai.goodPlace the shared helpers way finding, a collision step, tilt, a place it may walk to

Both games

The API is the same in both games; the species and their animation numbers differ. ai.anims(c) gives them for any creature, and the generic brains and c:walkTo / c:runTo / c:idle pick them by themselves. ai.brains() lists the species of the running game. An Ice Age animal's AI cannot run in Dinosaur Hunter or the other way round (each game is its own copy of the program, with its own species loaded); the generic brains bring the Ice Age style to Dinosaur Hunter's dinosaurs.

Performance

creature_hunt / creature_flee are checked after every creature's AI only while some mod listens. A Lua brain runs once per frame per creature: keep it short, and prefer the generic brains or c:stockAI() for crowds. Brains that fail 20 times in a row are removed (the console says so) and the species' own AI takes over again.