Overview
This page reads one complete script: an enemy that walks back and forth, waits at each end and tells other scripts when it turns. Each part links to the page that explains it.
package enemy
import "aego/log"
enum State {
Walk
Wait
}
script Patrol {
@export(min=0, max=20, unit="u/s")
var Speed float = 3
@export(min=0, max=50, unit="u")
var Distance float = 4
@export(min=0, max=5, unit="s")
var Pause float = 0.5
signal Turned(dir float)
var state State
var dir float = 1
var origin float
var turns int
func Ready() {
origin = node.Position().X
Turned.Connect(OnTurned)
}
func Update(dt float) {
if state == State.Wait {
return
}
p := node.Position()
p.X += dir * Speed * dt
node.SetPosition(p)
if dir > 0 && p.X >= origin+Distance || dir < 0 && p.X <= origin {
start Turn()
}
}
func Turn() coroutine {
state = State.Wait
yield wait(Pause)
dir = -dir
sr := node.Get<SpriteRenderer>()
if sr != nil {
sr.FlipX = dir < 0
}
state = State.Walk
Turned.Emit(dir)
}
func OnTurned(d float) {
turns++
log.Info("turn " + string(turns) + ", walking " + string(d))
}
}
The parts
package enemyandimportname the script's package and the engine packages it uses. See Files and packages.enum Statedeclares the two states. See Types.@exportshowsSpeed,DistanceandPausein the Inspector, with their range and unit. See Attributes.Readyruns once when the node enters the game,Updateonce per frame. See Scripts and lifecycle.nodeis the node the script is attached to;node.Get<SpriteRenderer>()reads one of its components. See Nodes, components and references.Turnis a coroutine:yield wait(Pause)pauses it forPauseseconds without stopping the game. See Coroutines.signal Turnedlets other scripts react to the turn. The script connects its own handler to it inReadyand emits it at the end ofTurn. See Signals.
Using it
- Save the script as
scripts/enemy/patrol.aes. - Select a node with a sprite, press Add Script in the Inspector and pick Patrol.
- Press Play. The node walks right, waits, turns and walks back.
- While the game runs, change Speed or Distance in the Inspector. The node follows the new values at once.