Help Support the Baja Engine! Donate to Breezeway Studios!
Cutscenes

Search:

Cutscenes the easy way with Coroutines


In a cutscene in your game, you essentially want a series of events to happen in order over a certain time period (ie, music cues, animation, etc). The Baja Engine interacts with your script by calling a function every frame. So, it seems like you would have to set up a bunch of variables that keep track of what events have already happened, a lot of big 'if then' clauses, etc so that your function set up stuff correctly each time it was called. But, there is a much easier way!

Lua has a concept called 'coroutines' that allow you to pause the execution of a function and then resume it later. This allows us to write a cutscene function that acts like a sequential series of cues (but is in reality still called every frame). The sample implementation below will show you how this works.

Sample Implementation


Code


myCutsceneDone=false

--coroutine.wrap turns our function into a coroutine
myCutscene=coroutine.wrap(function()

--first, open the spooky door (for 2 seconds)

doorTimer=0
while doorTimer<120 do
obj.spookyDoor.rot.y=obj.spookyDoor.rot.y+time*3
doorTimer=doorTimer+time
coroutine.yield() --this is the magic function! it pauses our function here and resumes it the next frame
end

--then, cue the scary music
scaryMusic:play()
--release the monster

while obj.monster.pos.z<10 do
obj.monster.pos.z=obj.monster.pos.z+time
coroutine.yield()
end

--we're done
myCutsceneDone=true
coroutine.yield()
end)

function perframe()
if not myCutsceneDone then doCutscene() end
end

Another Sample Implementation: Techdemo


The Techdemo included with the engine include a working example of a cutscene made with this concept.