full throttle stem™ game development€¦ · suggested materials for this tutorial include unity,...

50
Developed by: The teachers, students, and mentors in the Gaming Research Integration for Learning Laboratory™ (GRILL™) Summer 2014 Full Throttle STEM™ Game Development Challenge Problem and Resources DISTRIBUTION A: Approved for public release; distribution unlimited. Approval given by 88 ABW/PA, 88ABW- 2015-1605, 31 Mar 2015.

Upload: others

Post on 22-Jul-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

Developed by:

The teachers, students, and mentors in the Gaming Research Integration for Learning Laboratory™ (GRILL™)

Summer 2014

Full Throttle STEM™ Game Development

Challenge Problem and Resources

DISTRIBUTION A: Approved for public release; distribution unlimited. Approval given by 88 ABW/PA, 88ABW- 2015-1605, 31 Mar 2015.

Page 2: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

TABLE OF CONTENTS

1. CHALLENGE PROBLEM: FULL THROTTLE STEM™ GAME DEVELOPMENT .......................... 4

1.1. THE TOOLS ......................................................................................................................... 4 1.2. THE CHALLENGE .................................................................................................................. 4

2. EXTENSION #1: USING YOUR BODY TO PLAY VIDEO GAMES ........................................... 4

2.1. THE TOOLS ......................................................................................................................... 4 2.2. THE CHALLENGE .................................................................................................................. 5

3. EXTENSION #2: EYE-CONTROLLED VIDEO GAME ............................................................. 5

3.1. THE TOOLS ......................................................................................................................... 5 3.2. THE CHALLENGE .................................................................................................................. 5

4. EXTENSION #3: CUSTOMIZABLE KARTS AND PLAYERS .................................................... 5

4.1. THE TOOLS ......................................................................................................................... 5 4.2. THE CHALLENGE .................................................................................................................. 5

5. EXTENSION #4: RACING LINE OPTIMIZATION ................................................................. 6

5.1. THE TOOLS ......................................................................................................................... 6 5.2. THE CHALLENGE .................................................................................................................. 6

6. TUTORIALS OVERVIEW ................................................................................................... 7

7. LEARNING UNITY ............................................................................................................ 7

7.1. SCENE CREATION ................................................................................................................. 8 7.2. IMPORTING PACKAGES/ASSETS .............................................................................................. 8 7.3. APPLYING PHYSICS ............................................................................................................... 9 7.4. GAME PLAY ...................................................................................................................... 10 7.5. ADDITIONAL RESOURCES ..................................................................................................... 10

8. UNITY PUBLIC VARIABLES AND TAGS ........................................................................... 10

8.1. PUBLIC VARIABLES ............................................................................................................. 11 8.2. TAGS ............................................................................................................................... 14

9. UNITY TITLE PAGE TUTORIAL ........................................................................................ 16

9.1. TO BUILD A MENU: ............................................................................................................. 16

10. RUNNING A UNITY GAME ON A WEBSITE ..................................................................... 18

10.1. BUILDING THE GAME ......................................................................................................... 18 10.2. HTML CODE .................................................................................................................... 19 10.3. EMBEDDING THE UNITY3D FILE AND EDITING HTML ............................................................... 19 10.4. ADDING A MIME TYPE ....................................................................................................... 19

DISTRIBUTION A: Approved for public release; distribution unlimited. Approval given by 88 ABW/PA, 88ABW- 2015-1605, 31 Mar 2015.

Page 3: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

11. CREATING A MOVING CAR IN UNITY ............................................................................ 20

11.1. DOWNLOADING A PACKAGE ................................................................................................. 21 11.2. SETTING YOUR SCENE ......................................................................................................... 22 11.3. CUSTOMIZING THE CAR ...................................................................................................... 24

12. CREATING AN AUTONOMOUS CAR .............................................................................. 24

12.1. ADDING A SCRIPT ............................................................................................................... 24 12.2. CREATING THE PATH ........................................................................................................... 27 12.3. ADJUSTING THE VARIABLES TO MEET YOUR NEEDS .................................................................... 28

13. COUNTDOWN TIMER IN UNITY .................................................................................... 29

13.1. IMPLEMENTING TIMER GAME OBJECT ................................................................................... 29 13.2. TIMER SCRIPT .................................................................................................................... 30 13.3. ADDITIONAL DISPLAY METHOD ............................................................................................. 32

14. CREATING A 7 SEGMENT LED DISPLAY .......................................................................... 33

14.1. WIRING THE ARDUINO ...................................................................................................... 34 14.2. CHARACTER DESIGN ........................................................................................................... 36 14.3. ARDUINO PROGRAMMING .................................................................................................. 37 14.4. POST TUTORIAL ................................................................................................................. 40

15. CREATING AN OVERVIEW MAP IN UNITY ..................................................................... 41

15.1. CREATING THE CAMERA ...................................................................................................... 41

16. TRIGGER GAME OBJECTS .............................................................................................. 42

16.1. OBJECT INSPECTOR SET-UP ................................................................................................... 43 16.2. FUNCTIONALITY OF TRIGGER COMPONENT .............................................................................. 44 16.3. COMMUNICATING WITH OTHER SCRIPTS EXAMPLE .................................................................... 47 16.4. DEBUGGING ..................................................................................................................... 50

GAME DEVELOPMENT 3 Distribution A.

Page 4: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

1. CHALLENGE PROBLEM: FULL THROTTLE STEM™ GAME DEVELOPMENT

In an effort to continue to improve the customer’s experience, indoor go-karting facilities are looking toward providing consumers with racing games, modeled and programmed to reflect their actual tracks. This immersive environment will increase customer satisfaction, allowing users to practice on the simulated track prior to racing.

This challenge is a service-learning opportunity in which students will develop a virtual model of a karting facility. Students can import the virtual facility into a webpage, which will enable user-navigation control. Once created, successful implementation of the karting track would immerse users in a 3-D environment in which they have the opportunity to race in a variety of race and heat options.

1.1. THE TOOLS

Tools used to solve this challenge problem could include modeling software, such as SketchUp; computer scripting; and a game engine, such as Unity.

1.2. THE CHALLENGE

Create an immersive racing game of an indoor karting track to enable customers the opportunity to race autonomous vehicles and/or other players on their website or through a game engine.

2. EXTENSION #1: USING YOUR BODY TO PLAY VIDEO GAMES

Video games are fun and entertaining, but often encourage players to be sedentary. Many consumers of video games want to be more active. Leverage the interests of consumers to create a game that encourages physical activity.

This is an open-ended task where you get to decide the best way to encourage physical activity. A Zephyr BioHarness is a great way to track and log physiological data. The BioHarness has a multitude of potential applications, including real time monitoring of heart rate, breathing, temperature, posture, and acceleration in active field environments.

2.1. THE TOOLS

Find a system that will read data as it is changing and use it to control a video game. One example could be a racing game. If you decide to utilize the BioHarness in your game, consider downloading its SDK from http://zephyranywhere.com/zephyr-labs/development-tools/. To organize data of this device, Microsoft Excel and FreeMat (a free version of MATLAB) could be

GAME DEVELOPMENT 4 Distribution A.

Page 5: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

useful. Use modeling software, such as SketchUp, in conjunction with a gaming engine, like Unity, to create the simulation.

2.2. THE CHALLENGE

Create a video game where you have to be physically active to win.

3. EXTENSION #2: EYE-CONTROLLED VIDEO GAME

The Eye Tribe is a device that can track where a person’s eyes are looking on a computer screen. It is similar to Kinect, yet sits beneath the monitor, recording the eye movements of the computer’s user. The developers encourage people to experiment with the device in order to develop new applications for eye tracking. Use the Eye Tribe alongside any game engine to create an eye controlled game.

3.1. THE TOOLS

The tools for this challenge problem could include an Eye Tribe, Unity, and some coding. Research various software tools to find the necessary Eye Tribe functions and to identify possible compatible game engines.

3.2. THE CHALLENGE

Create a game that tracks eye movement to control character play using an Eye Tribe and a game engine.

4. EXTENSION #3: CUSTOMIZABLE KARTS AND PLAYERS

Players enjoy customized gaming experiences. Allow players to personalize their karts and characters. Using a 3D scanning device, these players may even be able to place themselves inside a virtual racing game.

4.1. THE TOOLS

Use modeling software, such as SketchUp or SolidWorks, 3D scanning devices, like AUTODESK 123D or Xbox Kinect, and a game engine, such as Unity.

4.2. THE CHALLENGE

Research and create a way in which users control their gaming experience. Players should be able to customize their karts, choosing from a variety of overlays, designs, and colors. They should also be able to select their racer.

GAME DEVELOPMENT 5 Distribution A.

Page 6: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

5. EXTENSION #4: RACING LINE OPTIMIZATION

Modeling and simulation can be used to assess the layout of a facility prior to spending time and money to implement a particular design. Go-karting tracks are a prime example in that the impact of barrier placement can be assessed prior to moving the track into a new configuration.

5.1. THE TOOLS

Familiarize yourself with the following topics:

• High school mathematics: Calculus, integration, optimization methods, series, geometry, algebra, etc

• High school physics: Velocity, acceleration, power, friction, etc • Programming: Any language you find suitable for this problem will be acceptable. MATLAB

or FreeMat are suitable, given the mathematical nature of this problem.

5.2. THE CHALLENGE

Create a method of calculating the optimal/ideal racing line for an indoor go-karting track. Be sure to consider the various physical restraints on the kart when formulating your problem (e.g. max speed, min/max acceleration, friction, minimum turning radius).

GAME DEVELOPMENT 6 Distribution A.

Page 7: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

6. TUTORIALS OVERVIEW

Wright Scholars, in collaboration with educators and the GRILL™ team, created the tutorials described below as possible solutions to solve the challenge problem. At the time of creation these were working tutorials; however, with software updates and changes in technology, additional steps may be required. Teachers are encouraged to communicate any issues, problems, or suggested changes to these tutorials to ensure the dissemination of helpful materials to support challenge problem implementation. Below is a description of each tutorial, followed by the full tutorials.

Table 1: Tutorials Provided for Challenge Problem

Challenge Problem Tutorials

Full Throttle Game Development

Learning Unity (Section 7), Unity Public Variables and Tags (Section 8), Unity Title Page (Section 9), Running a Unity Game on a Website (Section 10), Creating a Moving Car in Unity (Section 11), Creating an Autonomous Car (Section 12), Countdown Timer in Unity (Section 13), Creating a 7 Segment LED Display (Section 14), Creating an Overview Map in Unity (Section 15), Trigger Game Objects (Section 16)

7. LEARNING UNITY

This tutorial provides a general understanding of the concepts and vocabulary used to create games in Unity. This tutorial will not cover all of the functions available in Unity; rather it will introduce the environment.

Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources.

This tutorial includes the following topics: • Scene Creation

• Importing Packages/Assets

• Applying Physics

• Game Play

• Additional Resources

GAME DEVELOPMENT 7 Distribution A.

Page 8: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

7.1. SCENE CREATION

Download and install the latest version of Unity from the following website: http://unity3d.com/unity/download

1. Create a new project in Unity. When prompted, save the project in a newly created or empty folder.

2. When Unity opens, click GameObject in the toolbar and then click Create Other-> Cube. 3. With the cube selected in the hierarchy, modify the functionality of the game object to

create a ground for the game. Go to the Transform Component in the Inspector or select the scale icon in the top left hand corner of the screen. Also, make sure it is centered by zeroing out the position in the toolbar:

4. Go to GameObject -> Create Other -> Point Light. 5. Using the transform and light boxes in the Inspector window, make a light that is

satisfactory for the game. 6. Select the main camera in the hierarchy and select delete to remove it.

7.2. IMPORTING PACKAGES/ASSETS

Assets are the models, textures, sounds and all other content files used to design a game. Models can be created in software like SketchUp and imported into Unity.

1. Right Click in the Assets panel in the Project Browser. Hover over import package. Click character controller and click import.

2. Right Click in the Assets panel in the Project Browser. Hover over import package. Click skyboxes and click import.

3. Drag and drop the first person character onto the playing field. Zero out the position in the transform component in the Inspector window, and then use the arrows to adjust the position. This is the easiest way to make sure it is in the desired position. If the arrows do not appear, select the move position option in the top left hand corner.

GAME DEVELOPMENT 8 Distribution A.

Page 9: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

4. Modify the properties of the character such as movement and jumping. To do this, make sure you select the character in the hierarchy, and then change the values in the Character Motor script in the inspector window.

5. Extend the view of the First Person Controller by clicking the triangle in the hierarchy. Click on the main camera. In the Inspector window, select the Add Component button at the bottom. Select rendering -> select skybox.

6. Go to the skyboxes folder in the Project window (assets -> standard assets -> skyboxes) and click and drag the selected skybox to the box in the Main Camera’s Inspector.

7.3. APPLYING PHYSICS

In order for an object in a game to have convincing physical behavior, physics must be applied. You can apply various components and settings to objects so that they behave in a realistic way.

1. Import a new asset. This could be a model created in SketchUp and saved on the computer. Note: It must be a .dae or .fbx file.

a. In the Assets folder in the Project window, right click. b. Select Import New Asset. c. Navigate to where your model is saved and select it.

2. Drag and drop this model into the game area. Again, zero it out and use the arrows to move it to the desired position.

3. Move and scale the item/s so they work with your game. 4. Select GameObject and Create Empty. With the empty game object selected in the

hierarchy, click Component and then click Physics -> Box Collider. 5. Select the game object and drag it to your model in the hierarchy until the name is

highlighted, then drop it. 6. Extend the view of your model, and then select the game object. 7. Using the transform box or the arrows and boxes in the top left hand corner, adjust the

position and size of the box collider until it fits the item. Make sure it fits on the x, y, and z axis.

GAME DEVELOPMENT 9 Distribution A.

Page 10: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

Note: To change the view of the game, use the icon located the top right corner of the Scene view (pictured below). Alternatively, hold down the scroll wheel on the mouse to move the view and hold down the right click button to rotate the view.

7.4. GAME PLAY

1. Press the play button in the top center of the screen to play the game. 2. If the character can still go through your model/s, adjust the box colliders. 3. If desired, change the values of the character controller.

7.5. ADDITIONAL RESOURCES

Unity is a powerful engine with a variety of tools. Access resources and support from the following links:

• http://unity3d.com/learn

• http://unity3d.com/community

• http://docs.unity3d.com/Manual/UnityManualRestructured.html

8. UNITY PUBLIC VARIABLES AND TAGS

This tutorial documents how to enable objects to talk to each other in a Unity game. Scripts will use variables from other scripts, even when attached to other game objects. In addition, this tutorial documents how to use tags, and use these tags to trigger behaviors. Tags will also be used to access multiple objects all at once.

For this tutorial, you will need a computer and Unity.

This tutorial includes the following topics: • Public Variables • Tags • Fixing the Strobe Light Problem

GAME DEVELOPMENT 10 Distribution A.

Page 11: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

8.1. PUBLIC VARIABLES

1. Open Unity and select the Create New Project tab, choose the project’s location, and import the Character Controller and Terrain Assets packages.

2. Click Create. 3. Create a standard scene:

a. Click GameObject. b. Click Create Other. c. Click Terrain. d. Select the terrain in the hierarchy on the left side of the screen. e. Under Terrain (Script), select the paintbrush. f. Underneath Textures, select Edit Textures. g. Select Add Texture. h. Choose a grassy texture.

4. Add a controller: a. In the hierarchy, delete the Main Camera. b. In the project tab click Assets. c. Click Standard Assets. d. Click Character Controllers. e. Click and drag a First Person Controller into the scene. f. Select the box with four arrows in the upper left corner of Unity. g. Move the controller so that it is just over the terrain. h. Under GameObject, create a Point Light and place it near your controller. Make it bright,

and give it a large radius. Click play to ensure that it runs. 5. To make the light turn on and off when a character is moving or standing still:

a. Click Assets. b. Click Create. c. Click Javascript. d. Name the script Player_Moving. e. Double click on the script to open MonoDevelop. f. Copy and paste the following code into the Player_Moving script. To determine if the

character is moving, the last position needs to be compared with the current position of the character and a variable is needed to specify if the character is moving. Moving is Public.

Notes: • Public variables. If a variable is not defined as Public, nothing can read it. If another

script needs access to a variable from a script, make sure that it is Public.

GAME DEVELOPMENT 11 Distribution A.

Page 12: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

• Private variables. Private keeps the variables private and in the component view they will not show up. This prevents the component view from becoming cluttered with variables that should not be changed or touched.

private var lastPosition : Vector3; private var currentPosition : Transform; public var moving : boolean = false; function Start () { currentPosition = transform; lastPosition = currentPosition.position; } function Update () { if(lastPosition == currentPosition.position){ moving = false; } else{ moving = true; } lastPosition = currentPosition.position; }

6. You need a companion script to attach to the light. This script needs to be able to find the player object and read the moving variable from it. To do this, complete the following steps: a. Click Assets. b. Click Create. c. Click Javascript. d. Name the script Light_OnAndOff. e. Double click on the script to open MonoDevelop. f. Copy and paste the following code.

public var player : GameObject; function Start () { var light : Light; } function Update () { var movement = player.GetComponent(Player_Moving); if(movement.moving){ light.enabled = false; } else{ light.enabled = true; } }

7. Attach the scripts to objects: a. Select the First Person Controller. b. Click on Add Component.

GAME DEVELOPMENT 12 Distribution A.

Page 13: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

c. Add the Player_Moving script. d. Select Point Light. e. Click Add Component. f. Add the Light_OnAndOff script. g. Click play. Nothing should happen.

8. If a variable is defined at the beginning of a script, but not given an initial value, you can set the value, which will allow the script to work on any object that contains the Player_Moving script. To fix this, select the Point Light, and under Light_On And Off, choose a Game Object as the player. Make sure the First Person Controller is under Scene, it defines a particular instance of the First Person Controller. To make it is easier to find and distinguish; the First Person Controller can be renamed player, as shown below.

9. Click play. When you move the character, the light should begin to strobe. 10. In order to make the light constant, and not a strobe, you will need a timer. This timer will

start counting when the program detects that the character is standing still. Once it reaches a specific value, the light will turn on. Otherwise, it will remain off. This will counteract the strobe pattern of the light. To implement the timer, copy and paste the code below into Player_Moving. Max_Time and threshold have to be set.

Note: Set threshold to something very low, like 0.0001. Max_time can be set as you prefer, but do not set it to one or zero. The program will not run properly in that case. 1. private var lastPosition : Vector3; 2. private var currentPosition : Transform; 3. public var moving : boolean; 4. var threshold : float; 5. private var timer : int; 6. var max_time : int; 7. 8. function Start() 9. { 10. currentPosition = transform; 11. lastPosition = currentPosition.position; 12. var displacement = 0; 13. timer = max_time; 14. moving = false;

GAME DEVELOPMENT 13 Distribution A.

Page 14: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

15. } 16. 17. function Update() 18. { 19. displacement = currentPosition.position - lastPosition; 20. if (displacement.magnitude <= threshold ){ 21. timer = timer + 1; 22. } 23. 24. else{ 25. timer = 0; 26. } 27. if(timer >= max_time){ 28. moving = false; 29. } 30. else{ 31. moving = true; 32. } 33. lastPosition = currentPosition.position; 34. }

8.2. TAGS

Objects can be tagged in Unity, which allow you to refer to any or all of the objects with that tag.

1. Uncheck all the previous scripts that have been written in the object inspectors. 2. Select the First Person Controller. 3. At the top of the Inspector, click the Tag field to open a drop-down menu. 4. Select Player. 5. Create a point light. 6. Change the color to differentiate from the previous light. 7. Move it a distance away. 8. Create a cube. 9. Uncheck the mesh renderer to make the cube invisible. 10. Stretch it out to make it a wall. 11. Check the box collider is trigger. The goal is to turn one light off and the other on every time

you pass through the cube. You should get a scene somewhat like the picture below.

GAME DEVELOPMENT 14 Distribution A.

Page 15: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

12. Under the tag drop-down list, click the add tag button at the bottom. 13. Add tags light and wall to the tag list. 14. Tag both lights with the light tag and the cube with the wall tag. 15. Select the red light and in the Inspector, uncheck the Light section. 16. Create a new script called TwoLights, and open it up in MonoDevelop. Copy and paste the

following code.

var wall_tag : String; private var lights : GameObject[]; private var length : int; function Start() { var light : Light; } function Update() { lights = GameObject.FindGameObjectsWithTag("light"); length = lights.Length; } function OnTriggerEnter (object : Collider) { if(object.tag == "wall"){ for(var k : int = 0; k < length; k ++) { lights[k].light.enabled = !lights[k].light.enabled; } } }

17. Define the variable as wall_tag. To do this, attach the script to the player and type it in as the wall tag made earlier. This code creates an array of game objects, in this case all objects tagged as light. Then, since the collider of the cube is now a trigger, it triggers the

GAME DEVELOPMENT 15 Distribution A.

Page 16: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

OnTriggerEnter function, which is called whenever your character’s collider enters a trigger collider. Making the collider a trigger removes its ability to function as a normal collider.

18. In the OnTriggerEnter function, the code checks to see what tag the trigger has. If it is wall, it then triggers the for loop, which iterates through the array of lights, and changes each one to the opposite of what it was before. Run the game. When you pass through the invisible wall, one light will switch off, and the other will switch on.

It should be noted that these are just a few simple ways in which tags can be used. In a real game setting, you can tag special enemies that do different things when triggered.

9. UNITY TITLE PAGE TUTORIAL

This tutorial covers the basics of making a title page for a game in Unity 3D. The page will have a background image and interactive buttons that will take you to the main game when you are ready or display a help page.

9.1. TO BUILD A MENU:

1. Create a new Unity project, or if you have an existing project, open a new scene. If you are opening a new project, is not necessary to import any of the packages that the menu offers, but you will need to create two additional scenes. Name one Help (or something similar) and name the other one Main Game.

2. Create a plane by going to GameObject->Create Other-> Plane. To give the plane a texture/picture background, drag a picture file into the Assets pane. Then drag it onto the plane.

3. Create a directional light and use it to light up the plane. 4. Rotate and position the main camera to view the plane. Select the tools under the Edit

button and manipulate the camera in the scene window, or change the camera’s values in the inspector. Enable the camera preview if it is not already enabled, by expanding the camera menu under the camera inspector.

5. Import the image that you wish to use as your menu’s background into Unity by dragging it into the Assets menu. From there, texture the plane with it by dragging it from assets to the plane.

6. Create two GUI Texts. Give one the text Help and the other Play. 7. Create a script. Delete any default text in the script. Any programming language would

work, but this tutorial uses Unity JavaScript. Paste the code shown below into the script and

GAME DEVELOPMENT 16 Distribution A.

Page 17: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

save it. This script will allow your Help and Play buttons to take you to the Main Game or the Help Menu.

#pragma strict var isStart=false; var isHelp = false; var isRtm = false; // the above variables create selectable buttons in the inspector of any game object that the

script is added to function OnMouseEnter(){ //change text color when it is hovered over renderer.material.color=Color.red; } function OnMouseExit(){ //change text color renderer.material.color=Color.white; } function OnMouseDown(){ //the below code acts on the gameobject whose isHelp box in the inspector is checked if (isHelp==true) { Application.LoadLevel(1); //loads help scene } //the below code acts on the gameobject whose isStart box in the inspector is checked else if(isStart){ Application.LoadLevel(2); //loads level } //the below code acts on the gameobject whose isRtm box in the inspector is checked else if (isRtm == true){ Application.LoadLevel(0); //returns you to main menu if you have it set up to do so(not covered in tutorial) } else{ } } function Update(){ //quit game if escape key is pressed if (Input.GetKey(KeyCode.Escape)) { Application.Quit(); } }

8. Add the script to your active buttons by dragging it to the appropriate objects in the hierarchy.

9. View the buttons in the inspector. There will now be a script component for each button, and there will be a set of check boxes in the script component. Check the box that matches the button.

10. Go to the build menu and put the scenes in the correct order. The Main Menu should be Scene 0, the Help Menu should be Scene 1, and the Main Game Scene should be Scene 2.

GAME DEVELOPMENT 17 Distribution A.

Page 18: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

You should now have a Game Menu that will take you to your Help screen and the rest of the game.

10. RUNNING A UNITY GAME ON A WEBSITE

This tutorial explains how to take a Unity game built for the web and upload it to a website. You will need the ability to edit the website you plan to use, as well as the HTML file and Unity 3d file that Unity exports.

This tutorial includes the following topics: • Building the Game • HTML Code • Embedding the Unity File and Editing HTML • Adding a MIME Type

10.1. BUILDING THE GAME

1. Create a folder for the Unity game to be saved to, and place the folder wherever you choose.

2. To build the game in the Unity Editor, complete the following steps: a. Click File. b. Click Build Settings. c. Select Web Player from the list. d. Check Streamed. e. Click Build. f. Select the empty folder that was created and wait while the game builds itself.

3. Make sure that at the top of the Build window, the Game Menu scene has a 0 next to it. This will make the Game Menu scene the first scene that is loaded when the game starts.

4. To alter the resolution and presentation complete the following: a. Click edit. b. Click Project Settings. c. Click Player and select the globe icon for the web. Under Resolution and Presentation,

the default screen width and height can be altered. This is the best place to change the resolution of the player and the only place to change the resolution of the game.

Note: The game works differently if exported in different resolutions. Research has shown that the best resolution is 800 x 450. Export a second version of the game into another folder in the resolution the player will be in. By combining the smaller-resolution game file and the larger-

GAME DEVELOPMENT 18 Distribution A.

Page 19: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

resolution HTML file, a good resolution can be used in a larger web player. You can also change the resolution of the web player in the HTML code, but you have to change it in every location it is referenced, so it can be easy to overlook a section that must be edited.

10.2. HTML CODE

1. Inside the folder where you built the game will be an HTML file and a Unity 3d file. Open the HTML file in Notepad++ and copy the code. Paste it onto the webpage where you are going to upload the game.

2. In the file, there are two main places that you can edit: a. The first section of code allows specification of the URL of the game file. b. The second allows changing the title of the Web Player.

u.initPlugin(jQuery("#unityPlayer")[0], "example.unity3d"); <p class="header"><span>Unity Web Player | </span>Sample Assets</p>

3. Change the Sample Assets Section of the second line of code to reflect the title of the game you are going to upload to the website. For now, do not change the other code.

10.3. EMBEDDING THE UNITY3D FILE AND EDITING HTML

For the player to be able to access the file, the unity3D file must be embedded in the webpage. There are multiple ways to do this and it is best to comply with the suggestions and/or requirements of the company that is providing the webhosting for the website.

1. Make sure that the file name matches the .unity3d extension given in the third section of the code. If not, the player will search for the wrong file. You can now edit the size of the web player in the html file.

2. Make sure that the margin width specified under div. content matches the width of the window.

3. Save all changes and open the webpage normally to see if the game runs. If the game does not run, chances are the problem is with the MIME type. To attempt to rectify this problem, continue to the next section.

10.4. ADDING A MIME TYPE

MIME types tell a website what to do with non-html files. In this case, it is entirely possible that the server is not set up to read Unity 3d files and sends them to the player as an executable by default. In order to fix this, you will need access to the web.config file for your website. If you do not know where it is, it would be best to contact your web hosting service.

GAME DEVELOPMENT 19 Distribution A.

Page 20: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

1. Open the web.config file if you can access it. If you cannot access this file directly, or you do not know how to access this file, contact the hosting company. They may be capable of changing the web.config file. If so, have them add .unity3d files as a MIME type.

It is possible and probable that other MIME types already exist. There are two scenarios: one in which .unity3d files are added but not set up properly, and one in which they are not added in any capacity. For now, assume the latter.

2. Follow the code below, and insert the third line under system.webServer and the staticContent section. If there is no staticContent section, add it. Most of the code in specifying levels, if not all of it, should already exist. Ideally, you should only have to add the mimeMap line.

<system.webServer> <staticContent> <mimeMap fileExtension=".unity3d" mimeType="application/vnd.unity" /> </staticContent> </system.webServer>

3. Try running the game again. If it still does not work, it may be because .unity3d was already defined. If that is the case, add in the following code, which removes .unity3d before changing it.

<system.webServer> <staticContent> <remove fileExtension=".unity3d" /> <mimeMap fileExtension=".unity3d" mimeType="application/vnd.unity" /> </staticContent> </system.webServer>

Note: While research suggests that this process should work, it has not been tested. The web hosting services that we have access to do not appear to support .unity3d files, and we are unable to access the web.config files. There is no guarantee that this will allow a Unity game to run on your webpage.

11. CREATING A MOVING CAR IN UNITY

This tutorial documents how to create a moving car in the Unity Game Engine.

Materials for this tutorial include Unity and internet access, as well as a 3D modeled car. In this tutorial, you will use a Sodi-RX7 go kart. Also, make sure you have an Asset store account (it should be the same as your Unity account).

This tutorial includes the following topics: • Downloading a Package • Setting the Scene

GAME DEVELOPMENT 20 Distribution A.

Page 21: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

• Customizing the Car

11.1. DOWNLOADING A PACKAGE

1. Download and install the latest version of Unity from the following website:

http://unity3d.com/unity/download. 2. Go to the Assets Store, which is located on the following website:

https://www.assetstore.unity3d.com/en/. 3. Search for Sample Assets (beta). 4. Select the package and press the Open in Unity button. The Unity Project Wizard should

open.

5. If you have never opened Unity, it will prompt you to create and save a new project. Do so,

and Unity will open. 6. After Unity opens, the Assets Store will display. Select the import button to get the assets

into Unity.

7. Open the Sample Assets folder in the Project Window and navigate to the Car folder

(Sample Scenes folder-> Scenes folder -> Car folder). 8. When prompted, do not save the scene. It is no longer necessary.

GAME DEVELOPMENT 21 Distribution A.

Page 22: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

9. Once the new scene opens with the car, click File and Save Scene as. 10. Name the scene and save it in the folder where you saved the project.

11.2. SETTING YOUR SCENE

Since this is a free package in Unity that will soon be integrated, it is possible to use all scripts in the package. You can delete any scripts that you will not use in the project.

1. Remove the following items by selecting them in the hierarchy and pressing delete: a. Mobile Car Tilt Control b. Mobile Shader Replacements c. Extents d. Obstacles Dynamic e. Obstacles Static f. UI

2. In the Assets folder of the project window, right click and select Import New Asset. 3. Locate your modeled car and import it. Save the model as an .fbx file. 4. In the Assets folder, click the triangle to expand the view of your car model. This should

reveal the original model as well as multiple meshes. 5. In the Hierarchy, extend the car view and the SkyCar view. 6. Under SkyCar, select the first asset called vehicle_skycar_body_paintwork.

In the Inspector window, extend the Mesh box. Drag and drop the first part of your mesh into the box labeled mesh.

7. Repeat step 6 for vehicle_skyCar_body_parts and vehicle_skyCar_underside using the last

two meshes from your model. 8. If you have fewer than three meshes, silence whichever assets listed above that you did not

use by selecting them in the hierarchy and unchecking the box in the upper left hand corner of the Inspector window.

GAME DEVELOPMENT 22 Distribution A.

Page 23: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

9. If you have more than three meshes, create empty game objects by selecting Gameobject in

the toolbar, then Create Empty. Create one for each additional mesh you have. 10. Select each of your empty game objects and move them all into the skyCar asset by clicking

and dragging until skyCar is highlighted and then drop them. 11. Select each game object:

a. Click Component. b. Click Mesh. c. Click Mesh Renderer. d. Click Mesh Filter. e. Drag each additional mesh into the mesh box under the mesh filter in the inspector

window. 12. If the color is not correct, extend the mesh renderer box in the inspector window and drag

your selected material (from materials folder in assets) into the Element box.

13. Size all items correctly by using the Transform box in the Inspector window or highlight the

object in the hierarchy and select the scale tool in the upper left hand corner. Go to the transform window to verify all of the scale boxes are equal.

14. If the model has wheels, select vehicle_skyCar_wheel_(frontLeft-rearRight) (4 wheels) to silence the existing wheels in the model and uncheck the box in the upper left hand corner of the inspector window.

15. If the model does not have wheels, select “vehicle_skyCar_wheel_(frontLeft-rearRight)” (4 wheels) and use the scale and move tools or the position and scale sections in the transform box of the inspector window to place them appropriately.

16. Extend the vehicle_skyCar_underside view and silence the mud guards and suspensions. Notes: • You can delete anything that you have silenced. However, if you later decide that you

would like to use the deleted items, such as headlights or wheels, it is much easier to un-silence them than to re-add them into the model.

• Do not remove any of the wheel hubs; they are essential for movement.

GAME DEVELOPMENT 23 Distribution A.

Page 24: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

17. Click the play button at the top of the screen, the car should move when you click the arrow keys. If the car does not move, make sure you followed all of the previous steps accurately. Common mistakes include: • Deleting/Silencing Wheel Hubs • Not attaching the created game objects to the skyCar asset in the hierarchy

11.3. CUSTOMIZING THE CAR

At this point, there is a moving car in-game. However, it might not drive the way you want it to, so you may want to change some of the characteristic values.

1. Select Car in the hierarchy. 2. In the Inspector window, you should see a script called Car Controller (Script). Extend its

view and start changing the values.

Note: You should change one variable and verify that change is correct before making another change.

12. CREATING AN AUTONOMOUS CAR

This tutorial documents how to create an autonomous car that follows a given path in Unity. This is useful when creating a racing game because it allows the player to have opponents.

Materials for this tutorial include Unity and internet access in case questions or problems arise. This tutorial is part of the Creating a Racing Game series of tutorials, therefore you should already have a working car and track in the game engine.

This tutorial includes the following topics: • Adding a script • Creating a path from waypoints • Adapting a script to fit your needs

12.1. ADDING A SCRIPT

1. Open your project in Unity. 2. Enter the scene that has your moving car and track. 3. In the Assets folder in the project window, import the car you would like to use as the

autonomous car.

GAME DEVELOPMENT 24 Distribution A.

Page 25: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

4. Drag and drop the car into your scene and perform the transformations to place it in the desired position.

5. Add the box colliders to your autonomous car. 6. In the Assets folder in the project window:

a. Right click. b. Click create. c. Select javascript. d. Name the script AICar. e. Double click it.

7. When the Script Editor opens, delete the existing code and paste in the following code: var waypoints : Transform[];

var waypointRadius : float = 1.5;

var damping : float = 0.1;

var loop : boolean = false;

var speed : float = 2.0;

var faceHeading : boolean = true;

private var targetHeading : Vector3;

private var currentHeading : Vector3;

private var targetwaypoint : int;

private var xform : Transform;

private var useRigidbody : boolean;

private var rigidmember : Rigidbody;

// Use this for initialization

function Start() {

xform = transform;

currentHeading = xform.forward;

if(waypoints.Length<=0)

{

Debug.Log("No waypoints on "+name);

enabled = false;

}

targetwaypoint = 0;

if(rigidbody!=null)

{

useRigidbody = true;

rigidmember = rigidbody;

}

else

GAME DEVELOPMENT 25 Distribution A.

Page 26: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

{

useRigidbody = false;

}

}

// calculates a new heading

function FixedUpdate() {

targetHeading = waypoints[targetwaypoint].position - xform.position;

currentHeading = Vector3.Lerp(currentHeading,targetHeading,damping*Time.deltaTime);

}

// moves us along current heading

function Update(){

if(useRigidbody)

rigidmember.velocity = currentHeading * speed;

else

xform.position +=currentHeading * Time.deltaTime * speed;

if(faceHeading)

xform.LookAt(xform.position+currentHeading);

if(Vector3.Distance(xform.position,waypoints[targetwaypoint].position)<=waypointRadius)

{

targetwaypoint++;

if(targetwaypoint>=waypoints.Length)

{

targetwaypoint = 0;

if(!loop)

enabled = false;

}

}

}

// draws red line from waypoint to waypoint

function OnDrawGizmos(){

Gizmos.color = Color.red;

for(var i : int = 0; i< waypoints.Length;i++)

{

GAME DEVELOPMENT 26 Distribution A.

Page 27: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

var pos : Vector3 = waypoints[i].position;

if(i>0)

{

var prev : Vector3 = waypoints[i-1].position;

Gizmos.DrawLine(prev,pos);

}

}

}

Note: If you are entering the script by hand, make sure you enter all of the code correctly. If you miss one single thing, it will cause issues in your game. If Unity does not let you start playing your game, go to the compiler window and read the errors. If you double click on the error, it will take you to the error in the script.

8. Save and exit the script editor. 9. Drag the AICar script to your autonomous car in the hierarchy and when the name of the

car is highlighted, drop the script. This attaches the script. You can now see the script in the Inspector window when the Autonomous car is selected in the hierarchy.

12.2. CREATING THE PATH

1. Create an empty game object. 2. Place the game object where you want the car to go first. 3. Duplicate this game object; right click in the hierarchy and select copy, or select in the

hierarchy and click press control and D at the same time. 4. Move the copy to the next step in the path. 5. Repeat steps 3-4 until you have a complete path. Notes:

• The closer you place the game objects to each other, the smoother the car will drive. • It will make your life a lot easier if you name each game object by its number in the

path, especially if you have a very long path. 6. Select the car in the hierarchy. Expand the view of the AICar script. Expand the view of

Waypoints in the script in the Inspector window. In the box labeled Size, type in the number of game objects in your path and click enter.

A series of boxes labeled element 0 – element n (n being the number of game objects you have minus 1) should display.

GAME DEVELOPMENT 27 Distribution A.

Page 28: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

7. In the order of your path, starting at element 0, drag and drop each game object into its respective element box in the Inspector window. As this is happening, a red line should appear, revealing your path.

12.3. ADJUSTING THE VARIABLES TO MEET YOUR NEEDS

Play with the variables to get the effect you want for your car.

1. Waypoint Radius: Controls how close the car needs to come to the next game object to follow the path. If it is too big, the cars will not be on the path at all. If it is too small, the car will take a long time to reach the point.

2. Damping: The smoothness level as it travels from point to point. 3. Loop: Tells the car to start from the beginning after it reaches the last waypoint. 4. Speed: Controls how fast the car travels from waypoint to waypoint. 5. Face heading: Keeps the car facing front at all times.

Note: The script does not always know which way is the front of the car. If the car appears to be driving backwards, go into the script and change the sign in the following code from + to -:

if(faceHeading)

GAME DEVELOPMENT 28 Distribution A.

Page 29: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

xform.LookAt(xform.position+currentHeading);

13. COUNTDOWN TIMER IN UNITY

This tutorial will assist in the installation of a countdown timer within a Unity scene and present several options for GUI screening.

Suggested materials for this tutorial include Unity, the built in code editor MonoDevelop, and a functioning racing game.

This tutorial includes the following topics: • Implementing Timer Game Object • Timer Script • Additional Display Method

13.1. IMPLEMENTING TIMER GAME OBJECT

Download and install the latest version of Unity from the following website: http://unity3d.com/unity/download

1. Create a new project in Unity. When prompted, save the project in a newly created or empty folder.

2. Add a GUI Text game object: a. Click the GameObject tab towards the top of the screen. b. Click Create Other. c. Click GUI Text.

3. Make the following changes to the game object’s inspector window: a. Remove text from the Text field.

b. Choose center from the Alignment dropdown.

c. Change the font size to 60 in the Font Size field.

4. Create and edit a new script to attach to game object component: a. Double click GUI Text game object. b. In Inspector window, click Add Component. c. Click New Script. d. Click Create New Script and select C# format.

GAME DEVELOPMENT 29 Distribution A.

Page 30: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

e. Click the gear symbol in the upper right corner of the timer script (seen in picture below) and select Edit Script from the drop down menu. Script file will open in a new window through a program called MonoDevelop.

13.2. TIMER SCRIPT

1. Within MonoDevelop, copy and paste the following code into your script and click save. Change the name of the class in the script if your game object does not carry the same script name.

1. using UnityEngine; 2. using System.Collections; 3. public class CountdownTimer : MonoBehaviour { 4. 5. public int time; //Time variable can be set in inspector window or in code 6. public GUIText timer; //variable will be assigned to game object that contains

this script allowing the text string to be shown on the game screen 7. string text; 8. 9. void Start () { 10. time=120; 11. //Calls countdown method and begins countdown 12. StartCoroutine (countdown ()); 13. } 14. 15. // Update is called once per frame 16. void Update () { 17. //When space key is pressed, GUI text disappears 18. if (Input.GetKey ("space"))

Change Alignment

Gear symbol to edit Script

Remove Text

Change Font Size

GAME DEVELOPMENT 30 Distribution A.

Page 31: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

19. timer.text = ""; //Sets the text that will display through the GUI Text game object

20. } 21. 22. //method repeats every second allowing time to be decreased in one second intervals 23. IEnumerator countdown() 24. { 25. while (time > -1) 26. { 27. //converts time countdown to string. Value of text variable will

be shown on the game screen 28. timer.text = time.ToString(); 29. //Decreases time variable 30. time -= 1; 31. //Sets the rate that method is called to one second 32. yield return new WaitForSeconds(1); 33. } 34. //Text that is displayed after time reaches 0 35. timer.text = "Your Race Is Complete "; 36. } 37. }

2. Add the GUI Text game object to the Timer variable located in the GUI Text game object’s Inspector window. Timer set up is complete.

GAME DEVELOPMENT 31 Distribution A.

Page 32: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

3. Press the play button to view results.

13.3. ADDITIONAL DISPLAY METHOD

The code below provides an alternative way to display the text. Various changes need to be made to the script and with the GUI Text game object. Note: The following is a link to a website with additional

information: http://waynelee3d.com/blog/2014/05/25/unity-c-countdown-timer/ .

Replace the existing code with the code below.

1. using UnityEngine; 2. using System.Collections; 3. public class CountdownTimer : MonoBehaviour { 4. public int time;//Time variable can be set in inspector window or in code 5. public GUIText timer; //variable will be assigned to game object that

contains this script allowing the text string to be shown on the game screen 6. string text; 7. bool showCountdownScreen=true;//Used to control when the GUI text

displays 8. const int SCORE_WINDOW_ID = 1; 9. Rect scoreScreenRect = new Rect(Screen.width/2-50,20,100,50);// Sets

dimensions of text box that will be displayed 10. 11. void Start () { 12. time = 120; 13. //Calls countdown method and begins countdown 14. StartCoroutine (countdown ()); 15. } 16. 17. // Update is called once per frame

GAME DEVELOPMENT 32 Distribution A.

Page 33: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

18. void Update () { 19. //When space key is pressed, GUI text disappears 20. if (Input.GetKey ("space")) 21. timer.text = "";//Sets the text that will display through

the GUI Text game object 22. } 23. 24. //method repeats every second allowing time to be decreased in one second

intervals 25. IEnumerator countdown() 26. {Debug.Log (time); 27. while (time > -1) 28. { 29. 30. //converts time countdown to string. Value of text

variable will be shown on the game screen 31. text = time.ToString();//removes original

timer from screen 32. //Decreases time variable 33. time -= 1; 34. //Sets the rate that method is called to one second 35. yield return new WaitForSeconds(1); 36. } 37. //Text that is displayed after time reaches 0 38. timer.text = "Your Race Is Complete "; 39. } 40. void OnGUI() { 41. if(Input.GetKey("space")){ 42. showCountdownScreen = false; 43. } 44. if(showCountdownScreen) { 45. scoreScreenRect = GUI.Window(SCORE_WINDOW_ID

,scoreScreenRect, ScoreScreen, "TIMER"); 46. 47. } 48. } 49. 50. void ScoreScreen(int id) { 51. GUI.Label(new Rect(40,20,40,20), text); 52. } 53. 54. }

The code sets up a GUI window to display the text. It is no longer using the GUI Text game object to display the text. The picture below illustrates the intended layout of the timer.

14. CREATING A 7 SEGMENT LED DISPLAY

Indoor go-karting facilities may display digital clocks to indicate the racing time. 7 Segment LED displays are widely used to display decimal numerals in digital clocks and other electronic devices. This tutorial explains how to create a display from an Arduino that is capable of outputting most alphanumeric characters.

GAME DEVELOPMENT 33 Distribution A.

Page 34: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

For this tutorial, you will need the following:

• 1 x Arduino Board • 1 x Breadboard • 14 x LED Lights • 16 x Jumper Cables (7 of Color A, 9 of Color B) • (Recommended) 1 x 220 Ω Resistor • (Optional) Electrical Tape

This tutorial includes the following topics:

• Wiring the Arduino • Character Design • Arduino Programming • Post Tutorial

14.1. WIRING THE ARDUINO

1. Before getting started you need to familiarize yourself with an LED and how it should be placed.

2. LEDs are NOT reversible. On most LEDs, the longer end is the anode or positive pin. Make sure to press the lights in fully to prevent shorting the circuit.

3. Place the LED lights in the breadboard as shown below: a) Each pair of LED anodes should occupy a unique numbered row; however,

cathodes are allowed to plug in to common ground rows.

GAME DEVELOPMENT 34 Distribution A.

Page 35: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

Figure 1

b) If the circuit is completed correctly, there should be positive (+) ends of LED lights in rows 1, 2, 4, and 6. Arrange the LED lights so that they resemble the number eight.

c) Place cables of color A (shown as yellow in Figure 1 and blue in Figure 2) in to each of the unique LED anode rows (A2, A4, A6, J1, J2, J4, J6).

d) Attach ground cables (color B) to each of the remaining rows, and plug the other ends into two separate rows.

a. Connect these two rows with an additional wire. e) Connect a wire to either row, and attach the other end to an empty row. f) Connect this row to the ground strip on the right with a 220 Ω resistor. g) Connect the ground strip to the ground connector of the Arduino.

GAME DEVELOPMENT 35 Distribution A.

Page 36: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

h) Wire up each of the loose ends to the numbered slots on the Arduino, keeping track of which segments are connected to which slot.

Figure 2

Notes:

14.2. CHARACTER DESIGN

1. Create a character map to establish which of the seven segments will correspond to each character. Since the display only has seven segments, the characters will look similar to Figure 3.

GAME DEVELOPMENT 36 Distribution A.

Page 37: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

Figure 3

2. Make sure that ports 2 through 8 are connected to each segment of the LED display. 3. Determine, based on the LED configuration, which segments the Arduino should illuminate

when out putting a character. Note: It can be helpful to have a reference sketch to illustrate the physical arrangement of the seven segment display.

14.3. ARDUINO PROGRAMMING

The microprocessor on the Arduino board is programmed using Arduino programming language and the Arduino integrated development environment (IDE). You will need to download the software and upload the necessary code.

Download and install the latest version of Arduino IDE using the following link: http://arduino.cc/en/Main/Software Note: Choose a download that will work best for your computer.

1. Attach the Arduino board to the computer by connecting the USB adapter for the Arduino.

GAME DEVELOPMENT 37 Distribution A.

Page 38: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

2. Launch the Arduino software. This will open a window called sketch. 3. In the sketch begin the program by establishing variables that represent each of the seven

display slots. Use the following syntax for each plug, renaming the <variable name> to provide a unique name for each of the seven variables.

4. Use the void setup command to translate each of those unique variables into digital output pulses in Arduino.

5. Copy the following code for each variable in the void setup commands.

6. Create a void loop section of code.

In void loop, the code will follow a structured pattern that will look something like the following:

7. To output power to a slot, use the digitalWrite command. High essentially means on and Low means off.

8. To set a delay, use the delay() command. 9. Once the code is complete, upload it to your Arduino and let it run.

int <variablename> = <plug slot>;

pinMode(<variablename>, OUTPUT);

void loop() { place code in here that you want to run continuously }

Slot outputs that correspond to a given letter; Medium delay; Turn all slots off; Short delay; repeat

void setup() { place code in here that you only want to run once }

digitalWrite(<variablename>, <LOW/HIGH>);

delay(<time in milliseconds>);

GAME DEVELOPMENT 38 Distribution A.

Page 39: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

Below is an example piece of code:

int q1 = 2; int q2 = 3; int q3 = 4; //Set up variables “q1” through “q7” and int q4 = 5; //assign them numbers int q5 = 6; int q6 = 7; int q7 = 8; int delayTime = 300; void setup() { pinMode(q1, OUTPUT); pinMode(q2, OUTPUT); pinMode(q3, OUTPUT); //Read those variables as output slots pinMode(q4, OUTPUT); //on the board mapped to the ports that correspond pinMode(q5, OUTPUT); //to each variable’s value pinMode(q6, OUTPUT); pinMode(q7, OUTPUT); } void loop() { digitalWrite(q1, HIGH); digitalWrite(q2, HIGH); digitalWrite(q3, HIGH); //Send power to every slot digitalWrite(q4, HIGH); digitalWrite(q5, HIGH); digitalWrite(q6, HIGH); digitalWrite(q7, HIGH); delay(delayTime); //Wait for 300 milliseconds digitalWrite(q1, LOW); digitalWrite(q2, LOW); digitalWrite(q3, LOW); //Cut power to every slot digitalWrite(q4, LOW); digitalWrite(q5, LOW); digitalWrite(q6, LOW); digitalWrite(q7, LOW); delay(delayTime/4); //Wait for 75 milliseconds }

GAME DEVELOPMENT 39 Distribution A.

Page 40: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

14.4. POST TUTORIAL

1. Once a functioning LED display is produced, experiment with it. a. Swap the resistor for one with a higher or lower ohm rating. b. Change what the display says. c. Move the ground wire to a different port. d. Optimize use of wires. e. Change the LED lights to different sizes. f. Find different ways to wire the circuit. g. With more LED lights and breadboards, create multiple figures and spell out an entire

word.

GAME DEVELOPMENT 40 Distribution A.

Page 41: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

15. CREATING AN OVERVIEW MAP IN UNITY

Most games will need some sort of mapping system. One of the simplest, yet highly effective, types of Minimaps is a top-down view. A top-down view on a scene placed in the corner of the screen acts as a way for the player to get their bearings with the surrounding environment very quickly. This tutorial will walk through the process of creating a Minimap.

Note: This tutorial will assume that the reader has a basic knowledge of Unity. This tutorial will not cover subjects like project setup.

15.1. CREATING THE CAMERA

To create the Minimap: 1. In Unity, select the Game Object menu. 2. Select Create Other. 3. Select Camera.

4. Within the Inspector window, switch the Projection tab from Perspective to Orthographic. The preview should change (make sure the Camera tab is expanded to see the preview).

GAME DEVELOPMENT 41 Distribution A.

Page 42: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

5. Use the Size function within the Camera Inspector to shape the size of the view port that the Camera will see.

6. Use the Viewport Rect function within the Camera Inspector to shape the area that the Camera will display on the game screen.

After completing the above steps, you should have a top-down camera like the one shown below.

16. TRIGGER GAME OBJECTS

This tutorial will assist you in creating a trigger GameObject that can perform a needed function based on an object’s collision with another object. The following example pertains to a car racing game. The trigger is applied to a finish line and tracks when a car crosses the finish line.

GAME DEVELOPMENT 42 Distribution A.

Page 43: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

Suggested materials for this tutorial include a racing game in Unity.

This tutorial includes the following topics: • Object Inspector Set-Up • Functionality of Trigger Component • Communicating with Other Scripts/Classes • Debugging

16.1. OBJECT INSPECTOR SET-UP

1. Create an empty GameObject: a. Click GameObject. b. Click Create Empty.

2. Apply a collider to the GameObject: a. Click and highlight empty GameObject. b. Click Component tab within Unity. c. Select Physics. d. Choose a type of collider (box collider used in this tutorial).

3. Adjust collider to fit desired area by adjusting the scale in the inspector. You should place the collider where you want it to interact or trigger other game objects. It is best to keep the collider from overlapping with any other GameObject that has a collider such as the terrain.

GAME DEVELOPMENT 43 Distribution A.

Page 44: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

4. Check the Is Trigger box in the GameObject‘s Inspector window. By checking Is Trigger, the collider will no longer apply the physics function to itself. If the physics function created with a collider is desired, add another collider and do not check Is Trigger.

5. If collider correspondence with an existing GameObject is desired, drag and drop the empty

game object onto the existing GameObject within the Hierarchy window to make the empty object and collider a child of the existing GameObject.

16.2. FUNCTIONALITY OF TRIGGER COMPONENT

1. To enact a function to the trigger event, add a script to the GameObject containing the Is Trigger collider by clicking Add Component within the Inspector window.

2. Create New Script in C# format. 3. Click the gear located in the upper right corner of the new Script tab to open the drop down

menu and click Edit Script.

GAME DEVELOPMENT 44 Distribution A.

Page 45: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

4. Add the following code to the script that will perform your desired function.

1. using UnityEngine; 2. using System.Collections; 3. 4. public class CarTrigger : MonoBehaviour { 5. 6. void Start(){ 7. 8. } 9. 10. void Update(){ 11. 12. } 13. }

5. Add OnTriggerEnter function/method. You must attach the script that uses OnTrigger methods to the game object that contains the collider marked Is Trigger. For additional information, visit the following website: http://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html 1. using UnityEngine; 2. using System.Collections; 3. 4. public class CarTrigger : MonoBehaviour { 5. 6. void Start(){ 7. 8. } 9. 10. void Update(){ 11. 12. } 13. 14. //When a game object with a rigidbody and collider makes contact with the trigger

collider, the method below is entered. The “collider” variable refers to the non-trigger collider that was involved.

15. void OnTriggerEnter(Collider collider){ 16. 17. } 18. 19. }

Note: Additional methods such as OnTriggerExit and OnTriggerStay may also be used if you would like to trigger an event when the object leaves the area or stays in it for an extended period of time. 6. Add code that performs the desired function once collision has occurred. The code shown

below creates a counter that tracks how many times the car passes through the trigger object. For the racing game, it counts how many times the car passes the finish line.

GAME DEVELOPMENT 45 Distribution A.

Page 46: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

1. using UnityEngine; 2. using System.Collections; 3. 4. public class CarTrigger : MonoBehaviour { 5. 6. int lapCount=0; //initialize counter variable 7. 8. void Start(){ 9. 10. } 11. 12. void Update(){ 13. 14. } 15. 16. //When a game object with a rigidbody and collider makes contact with the trigger

collider, the method below is entered. The “collider” variable refers to the non-trigger collider that was involved.

17. void OnTriggerEnter(Collider collider){ 18. lapCount++; //Increases the lap counter by 1 each time collision with the finish line

is detected 19. } 20. 21. }

7. Add tag specification. The tag referenced in the script will be applied to a car game object to

distinguish between other cars or game objects with colliders.

Note: Tags can be compared with rigidbodies as well using collider.attachedRigidbody.CompareTag(TagName). Enabling .CompareTag() method will cause the script to search for the tag reference throughout your project scene. This means tag is easy to access, but be careful of multiple object assignments to one tag.

1. using UnityEngine; 2. using System.Collections; 3. 4. public class CarTrigger : MonoBehaviour { 5. 6. int lapCount=0; //initialize counter variable 7. 8. void Start(){ 9. 10. } 11. 12. void Update(){ 13. 14. } 15. 16. //When a game object with a rigidbody and collider makes contact with the trigger

collider, the method below is entered. The “collider” variable refers to the non-trigger collider that was involved.

17. void OnTriggerEnter(Collider collider){ 18. if(collider.CompareTag(“Player”)) //This tag will be linked to car game object in the

game

GAME DEVELOPMENT 46 Distribution A.

Page 47: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

19. lapCount++; //Increases the lap counter by 1 each time collision with the finish line is detected

20. } 21. 22. }

8. Add tag to GameObject by clicking the Tag drop down menu in the Inspector window of the game object you want to collide with the trigger game object. Assign new tag by clicking Add Tag (Note that the new tag name is accessible to all other game objects as well).

Note: You should apply tag to game object that corresponds to script reference. If you used collider.CompareTag(TagName) then the tag must be on the game object that contains a collider and the same for a rigidbody component if you use collider.attachedRigidbody.CompareTag(TagName).

16.3. COMMUNICATING WITH OTHER SCRIPTS EXAMPLE

The following script corresponds to an End Game Text script that displays the results of the race. To display the number of laps the car completed, it must communicate with the script that tracks the number of laps created above. 1. Reference the CarTrigger script in the EndGameText script on line 5, the script can call any

public function within the CarTrigger script.

GAME DEVELOPMENT 47 Distribution A.

Page 48: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

1. using UnityEngine; 2. using System.Collections; 2. 3. public class CarTrigger : MonoBehaviour { 4. 5. int lapCount=0; //initialize counter variable 6. 7. void Start(){ 8. 9. } 10. 11. void Update(){ 12. 13. } 14. 15. //When a game object with a rigidbody and collider makes contact with the trigger

collider, the method below is entered. The “collider” variable refers to the non-trigger collider that was involved.

16. void OnTriggerEnter(Collider collider){ 17. if(collider.CompareTag(“Player”)) //This tag will be linked to car game object in the

game 18. lapCount++; //Increases the lap counter by 1 each time collision with the finish line

is detected 19. } 20. 21. //method will return the number of laps completed by car when it is called 22. public int LapCount(){ 23. return lapCount; 24. } 25. 26. }

GAME DEVELOPMENT 48 Distribution A.

Page 49: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

1. using UnityEngine; 2. using System.Collections; 3. 4. public class EndGameText : MonoBehaviour { 5. public CarTrigger other; //Creating variable named “other” that references

CarTrigger script 6. int numLaps=0; 7. const int SCORE_WINDOW_ID = 1; 8. Rect scoreScreenRect = new Rect(550,100,400,400); 9. bool showScoreScreen; 10. 11. void Start(){ 12. } 13. 14. void Update(){ 15. numLaps=other.LapCount();//assigns the variable numLaps to the number of laps

that are counted in the CarTrigger script 16. OnGUI(); 17. } 18. void OnGUI() { 19. if(Input.GetKey("space")){ 20. showScoreScreen = true; 21. } 22. if(showScoreScreen) { 23. scoreScreenRect = GUI.Window(SCORE_WINDOW_ID ,scoreScreenRect,

ScoreScreen, "Results"); 24. } 25. } 26. 27. void ScoreScreen(int id) { 28. GUI.Label(new Rect(50,50,350,350), "Player 1 Number of Laps: “+numLaps); 29. } 30. }

2. Assign the variable “other” within EndGameText script in the inspector to complete

correspondence between the two scripts. Double click on the object that would contain the script that calls another script’s methods (in this case it would be EndGameText).

3. Locate the Inspector window and make sure this game object’s Inspector window stays in view throughout the next steps.

4. Drag and drop the game object that contains the referenced script (in this case it would be the empty game object created earlier) from the hierarchy window into the open variable position within your Script tab (EndGameText tab).

GAME DEVELOPMENT 49 Distribution A.

Page 50: Full Throttle STEM™ Game Development€¦ · Suggested materials for this tutorial include Unity, SketchUp, and an internet connection to access additional resources. This tutorial

16.4. DEBUGGING

Implement Debug.Log(ErrorMessage); into different points of your code to verify the code is working properly and identify the region of error. In this scenario, use Debug.Log(Lap Count: +numLaps); in the EndGameText script after the LapCount() method is called to test that the collider is being triggered and that the scripts are communicating as intended.

GAME DEVELOPMENT 50 Distribution A.