Monday, April 14, 2014

Unity3D Native 2D - Game Flow + Event Listeners

Source Code and executable can be found in the post here

Last time, I talked about creating animations using the sprites from the sprite sheet and using them to set up various animation states in the Animator Controller.  This time, I'm going to take a quick detour before continuing onto the code that controls the Animator Controller.  Today, I want to talk about the overall game flow and how that is represented in this project.

Let's say the player starts up the game and enters the main menu. How do we go from this:


to this:


There needs to be some type of manager that knows that when the player presses start, the game needs to transition into some other game state which spawns the columns, scrolls the background, enables player input on the bird, etc.  One way to solve this method is to use a state machine.  Logically, we can represent each transition in the game as a separate state.  Take this project for example, I could represent the main menu as one game state, and create another game state called "In Game" that we can transition to and from.

One possible, and simple, implementation idea might be to have a enum variable that represents each state. Then in an update method, you can have if statements that will contain logic to deal with each state.  However, you may notice that we spend a lot of cycles doing useless work.  The only time that we transition from the main menu to the game state is when the user presses the start button.  So then, how do we avoid the need to constantly poll and perform unnecessary state checks?  One solution is to use event listeners.  

Event listeners allow objects to listen to specific events they are interested in, and respond when those events are triggered.  For example, the game logic can listen for the "Start button clicked" event, and when that event triggers, performs the necessary tasks to start a game.  Here's an example of my Message class.


So in this project for example, I have a Game.cs script which manages the flow of the game.  The Game.cs script is interested in when the player clicks the start button so it can tell other systems to begin and start a game.  To achieve this, we do something like the following :

Then to trigger the startGame event, we do something like :

One downside to this implementation is that debugging can be a little more difficult.  Because of the fact that code is no longer centralized in one core file, debugging and stepping through issues may require the programmer to follow the bread crumb trail and back track through various files.

No comments:

Post a Comment