I’ve seen a few people asking about how to do seperate screens for, say, title screens and game-over screens etc… so I thought I’d post how I do it: I have a global “screen” variable that holds the current screen. Every frame I call its “tick” and “draw” methods (I like to do the update logic seperate to the draw logic).
Each screen is just a class that implements these methods (you could use a common base class for it, if you wanted). When I want to move to different screen, I instantiate the next screen and set it to the current one.
In the example below there is a title screen that displays for 100 frames, then the main “game” loads (this is where you’d kick off your actual game object). When you touch the screen in game mode, then it’s gameover, and the game over screen show for 100 frames before going back to the title. It’s not fancy, but it works!
screen = nil
function changeScreen(s)
screen = s
end
function setup()
changeScreen(ScreenTitle())
end
function draw()
screen:tick()
screen:draw()
end
function touched(t)
if screen.touched ~= nil then
screen:touched(t)
end
end
-- @@@@@@@@@@@@@@@@@@
ScreenTitle = class()
function ScreenTitle:init()
self.frame = 0
end
function ScreenTitle:tick()
self.frame = self.frame + 1
if self.frame > 100 then
changeScreen(ScreenGame())
end
end
function ScreenTitle:draw()
background(40, 40, 50)
text("Title Screen", WIDTH / 2, HEIGHT / 2)
end
-- @@@@@@@@@@@@@@@@@@
ScreenGame = class()
function ScreenGame:init()
-- self.game = MyGame()
end
function ScreenGame:tick()
--self.game:tick()
end
function ScreenGame:draw()
-- self.game:draw()
background(48, 46, 37, 255)
text("g a m e", WIDTH / 2 + math.random(-10,10), HEIGHT / 2)
end
function ScreenGame:touched()
changeScreen(ScreenGameOver())
end
-- @@@@@@@@@@@@@@@@@@
ScreenGameOver = class()
function ScreenGameOver:init()
self.frame = 0
end
function ScreenGameOver:tick()
self.frame = self.frame + 1
if self.frame > 100 then
changeScreen(ScreenTitle())
end
end
function ScreenGameOver:draw()
background(41, 56, 56, 255)
text("GAME OVER!", WIDTH / 2, HEIGHT / 2)
end