Coroutine Sequences
I am experimenting with a system for creating a sequence of actions using Lua coroutines. This allows you to define a bunch of behavior at startup and let the game just run without having to keep track of a lot of states.
You can add coroutines to entities and they will be executed in order. The first one will complete, and then the next one will start.
A channel parameter allows you to have separate stacks of commands so you can have multiple sequences running on the same object. For example, you might have one channel that controls entity colors while another channel is controlling position.
function Script:Start() local MotionChannel = 0 local ColorChannel = 1 local turnspeed = 1 local colorspeed = 3 --Rotate back and forth at 1 degree / second self:AddCoroutine(MotionChannel, ChangeRotation, 0, 45, 0, turnspeed) self:AddCoroutine(MotionChannel, ChangeRotation, 0, -45, 0, turnspeed) self:LoopCourtines(MotionChannel)--keeps the loop going instead of just running once --Flash red and black every 3 seconds self:AddCoroutine(ColorChannel, ChangeColor, 1, 0 , 0, 1, colorspeed) self:AddCoroutine(ColorChannel, ChangeColor, 0, 0, 0, 1, colorspeed) self:LoopCourtines(ColorChannel)--keeps the loop going instead of just running once end
There's no Update() function! Where do the coroutine functions come from? These can be in the script itself, or they can be general-use functions loaded from another script. For example, you can see an example of a MoveToPoint() coroutine function in this thread.
The same script could be created using an Update function but it would involve a lot of stored states. I started to write it out actually for this blog, but then I said "ah screw it, I don't want to write all that" so you will have to use your imagination.
Now if you can imagine a game like the original Warcraft, you might have a script function like this that is called when the player assigns a peasant to collect wood:
function Script:CollectWood() self:ClearCoroutines(0) self:AddCoroutine(0, self.GoToForestAndFindATree) self:AddCoroutine(0, self.ChopDownTree) self:AddCoroutine(0, self.GoToCastle) self:AddCoroutine(0, self.Wait, 6000) self.AddCoroutine(0, self.DepositWood, 100) self:LoopCoroutines(0) end
I wonder if there is some way to create a sub-loop so if the NPC gets distracted they carry out some actions then return to the sequence they were in before, at the same point in the sequence.
Of course this would work really well for cutscenes or any other type of one-time sequence of events.
6 Comments
Recommended Comments