Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Creating E-Learning Games with Unity

You're reading from  Creating E-Learning Games with Unity

Product type Book
Published in Mar 2014
Publisher
ISBN-13 9781849693424
Pages 246 pages
Edition 1st Edition
Languages
Author (1):
David Horachek David Horachek
Profile icon David Horachek

Table of Contents (17) Chapters

Creating E-Learning Games with Unity
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Introduction to E-Learning and the Three Cs of 3D Games 2. Interactive Objects and MissionMgr 3. Mission One – Find the Facts 4. Mission One – Future Proofing the Code 5. User Interfaces in Unity 6. NPCs and Associated Technology 7. Mission Two – Testing a Player's Learning 8. Adding Animations 9. Synthesis of Knowledge 10. An Extensible Game Framework Pattern in Unity Index

Chapter 4. Mission One – Future Proofing the Code

We have designed and implemented a working first pass on the first mission of our game. Take a moment to step back and celebrate! To make sure we can finish creating the last two levels and finish polishing this level, we will need to revisit some of the code we have already written to ensure it is extensible to meet the needs of the other two missions in our game.

We will restructure the existing game into a number of subscenes. Then we will reintegrate the code so that the game can support multiple scene files; hence, it will support multiple levels. We will extend our interactive object system so that it supports more general purpose operations with transforms, which are necessary for future mission requirements. Finally, we will finish the trivia cards with an eye towards testing and application for the last levels.

In this chapter, we will cover the following topics:

  • Reorganizing our GameObjects in the Scene view

  • Adding new scenes to the...

Reorganizing our GameObjects in the Scene view


The following GameObjects will be the focus of our design activities in this chapter:

  • GameMgr: This script will handle the choreography between the game and its particular states. It will hold the logic that moves the game from the main screen and between the individual levels.

  • PlayerData: This script will hold the game instance-specific attributes of the player. This will include variables such as score and current level.

  • Game: This is the GameObject that holds the scripts necessary for game control. It will hold the GameMgr script as well as the MissionMgr script.

  • _level1: This class will hold all of the objects that are specific to the first level.

  • _global: This class will hold all of the objects that are global or persistent across all game levels as shown in the following screenshot:

Taking an already working system of code and reworking it so that it is more extendible is called Refactoring. By refactoring our game into a number of scene files...

An introduction to Finite State Machines


A common strategy in game play programming (and computer science in general) is to model a system in terms of discrete objects and their interactions with one another. To do this requires us to understand what the participants are in a system, how they operate in different scenarios, and how they change states.

The Finite State Machine (FSM) is one such technique. With this, the idea is to model the behavior of the object in a number of code blocks. Inside each one, you put the specific code for that block that makes it unique. You also determine what scenarios cause an object to switch from one block (state) to another. Because each state is an encapsulation, it makes your code extensible and maintainable (which is a great thing!).

Implementing an FSM in a game

While there are many ways of programming an FSM, we will commonly encounter two strategies as game programmers on our e-learning example. Each one has its own unique structural components, benefits...

Implementing the GameMgr script


Let's implement the GameMgr script so that it can manage the loading (and future unloading) of scene files and assets. Implementing this in a flexible way now will make our game more extensible when we have future levels to add. It can be implemented by performing the following steps:

  1. Recall that we have already created an empty script named GameMgr and attached it to the Game GameObject. If you have not already done this, no worries; just create a new script now, and attach it.

  2. In order for GameMgr to do its job, it will act as a mediator between popupMenu and the scene files of the game. When GameMgr receives a message to change its state, it will load and unload the appropriate scene files.

  3. It is important that at this point we have added the LEVEL1 scene file to the build settings; if you have not yet done this, make sure it has been added now.

  4. We will use a custom enumeration in this class to build a state machine. This is a data structure that will let us...

Reflecting on our code changes


Before we can test our code properly, let's reflect on what we have done. While we have made our game framework more flexible and extensible, we have also broken some assumptions from before that need repairing as discussed in the following points:

  • The MissionManager class has been renamed to Game. This means that all scripts that used to do a GameObject.Find("MissionManager") need to be updated to Find("Game").

  • We have separated some objects into the MAIN scene and some into the LEVEL1 scene. This means that objects that have a reference to an object that is now in another scene will be broken. To repair these, we need to modify the code for the object in the scene. See SetupSceneOne for an example of this.

Analyzing code functionality


We can test our work now by switching to the MAIN scene file and clicking on Play. Notice right off the bat that there is one GameObject in the Hierarchy view, the _global object that holds the main camera, the Game, and the Player. We should also see the main menu pop up right away as shown in the following screenshot:

Clicking anywhere on the pop up sends a message to GameMgr to switch the level to Level1. Upon doing so, we should notice two GameObjects in the hierarchy view: the _global object and the level1 object (which has the terrain, monument, flag holders, and directional light) as shown in the following screenshot. By using this structure of relating the scene name to the name of a game object at the root of the project view, we will make unloading of levels really easy.

Updating some systems


We introduce a new class, PlayerData, to track the current level and points accrued of the player. To make use of this new functionality, we need to update some systems by performing the following steps:

  1. Switch to the LEVEL1 scene. Double-click on the PlayerData script to begin editing it.

  2. Add a public int score and a public GameState level; note that in order to create an instance of the enumeration defined inside the GameMgr class, we need to prefix with GameMgr as shown in the following code:

    public class playerData : MonoBehaviour {
    public int score;
    public GameMgr eGameState;
  3. Add a public method called addScore(int dScore). This method will be used by the different systems (primarily MissionMgr), to add score to the player's record. Note that since we use an integer for score, we could use this same method to add score or penalize the player (by adding negative scores) as shown in the following code:

    public void AddScore(int dScore)
    {
      score += dScore;
    } 
  4. Add a public...

Making the ScorePlate active


Let's create a simple script to update the text field of this score as shown in the following screenshot:

The following script will update the text field in the upper-right corner of the screen so that it reflects the score stored in PlayerData:

  1. Switch to the MAIN scene. Create a new script, and name it scoreScript.cs.

  2. Attach an instance of this script to the score GameObject.

  3. In the start method of this script, find the GameObject named Player, and then store a reference to the PlayerData component on this script.

  4. The score script needs to update a member of the GUIText GameObject score, so the update loop that this script should be called from is OnGUI(). Inside this loop, we check for a PlayerData component as shown in the following code:

    void OnGUI() { }
    GameObject go = GameObject.Find("Player")
  5. If there is one, we take the score value from PlayerData and assign it to the text field of the textbox. Note that we have to use the C# helper function .ToString() to convert...

Updating the player motion algorithm


To make our game character move through the level more smoothly, we will modify the motion algorithm. Instead of relying on gravity on the rigid body to keep the player anchored to the ground, we will cast a ray downward and glue the player to the polygon directly below. In this way, the curvature of the terrain will play less of a role in restricting the player. This can be achieved by performing the following steps:

  1. Switch to the MAIN scene, and double click on the PlayerControls script on the player. In the UpdateMovement() method, directly after the CharacterController.Move() method is called, declare a RayCastHit class named hitInfo as shown in the following code. This class will be used to return the position of the polygon from a raycast that is directly below the player. By invoking a raycast downward, we can check what other GameObject is intersected and use this information to glue the player to the ground directly at the point of contact:

    RayCastHit...

Playing the level!


We can test our work now by playing the level. Start the level by running the MAIN scene. Notice the main menu pop-up window that presents the game and waits for the player to click to begin. Once level one loads, drive the player around the level to find the five missing flags. Once found, press their icon in the inventory to read the information about each state as these information card Prefabs have now been updated with interesting trivia about each region. Once all five are found, the system will tell you to return them to the monument, at which time the flags will return, and the mission will be done. Note the score updating when each mission is updated and the smooth character motion across the terrain.

Summary


We have engaged in an iteration on our game program and refactored the working level from the last chapter into multiple scenes. We have created a GameMgr class to handle the new game states for our game, and we have associated individual level scenes with unique states; a good practice for flexible and extensible programming. We updated the camera, score, and PlayerData systems to add further polish and functionality to our game. Next, we will learn about the various user interface options that Unity provides. We will use these to develop a HUD system for our game that will meet the final needs of our e-learning game.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Creating E-Learning Games with Unity
Published in: Mar 2014 Publisher: ISBN-13: 9781849693424
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}