Skip to content

Instantly share code, notes, and snippets.

@nasser
Created May 4, 2014 14:19
Show Gist options
  • Save nasser/cd149b2c51e40c27218e to your computer and use it in GitHub Desktop.
Save nasser/cd149b2c51e40c27218e to your computer and use it in GitHub Desktop.
/*
each of your game states can inherit from ofBaseApp if you're just
overriding update and draw and the like. this is the simplest thing
you can do and that's the example included here. other states besides
MenuState can be implemented in the same way.
more generally and more powerfully, you could create a GameState class
that all of your states inherit from. there, you would define methods
to override like update and draw, but also methods to handle switching
between states that each state can override. this requires an understanding
of C++ inheritance, virtual methods and abstract classes.
http://www.cplusplus.com/doc/tutorial/polymorphism/ (ignore friendship)
http://www.cprogramming.com/tutorial/lesson20.html
*/
// in GameState.h
class MenuState : public ofBaseApp {
public:
void update();
void draw();
// additional, state-specific methods and variables
};
// in MenuState.cpp
#include "testApp.h"
#include "SomeOtherState.h"
void MenuState::update() {
// MenuState's update
// when you are ready to switch to a new state
((testApp*)ofGetAppPtr())->switchState(new SomeOtherState());
}
void MenuState::draw() {
// MenuState's draw
}
void MenuState::keyPressed(int key) {
// MenuState's keyPressed
// when you are ready to switch to a new state
((testApp*)ofGetAppPtr())->switchState(new SomeOtherState());
}
// in testApp.h
class testApp : public ofBaseApp {
// a pointer to a ofBaseApp object that will be the game state
// is has the same type as testApp (ofBaseApp) to guarantee that
// methods called on testApp will be available in gameState
ofBaseApp* gameState;
// called by gamestates when they want to transition to a new state
void switchState(ofBaseApp* newState);
// the rest of your usual testApp declaration
};
// in testApp.cpp
void testApp::setup() {
gameState = new MenuState();
gameState->setup();
}
void testApp::update() {
gameState->update();
}
void testApp::draw() {
gameState->draw();
}
void testApp::keyPressed(int key) {
gameState->keyPressed(key);
}
// etc
void testApp::switchState(ofBaseApp* newState) {
// clean up old gameState
delete gameState;
// update pointer so that update, draw, and input calls go to new state
gameState = newState;
// do any state transition logic here, e.g. clean up data, fade between scenes etc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment