Check Plagiarism

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 54

3D Racing Car game Dr Drifty

Using Unity Game Engine.

By:

Amir Taimour Shah


Reg No: 14-F-AWKUM-USM-BCS-SOFT-09

A Thesis Submitted to

Abdul Wali Khan University, Mardan

In Partial Fulfillment of the Requirements of the Degree

BACHELOR OF COMPUTER SCIENCE IN SOFWARE (BCS-SOFT)

Abdul Wali Khan University,


Mardan, Pakistan
Spring 2018
Final Approval

This Project Report title

3D Racing car game Dr. Drifty


Using Unity game engine.
By:
Amir Taimour Shah
Reg No: 14-F-AWKUM-USM-BCS-SOFT-09

Has been approved for the award of BCS-SOFT Degree

External Examiner: _____________________________________________________


Dr. Aftab Ahmed
Assistant Professor, Department of Computer Science, AWKUM.

Internal Examiner: _____________________________________________________


Mr. Shahid Akbar
Lecturer, Department of Computer Science, AWKUM

Project Coordinator: ____________________________________________________


Mr. Salman Khan
Lecturer, Department of Computer Science, AWKUM

Supervisor: ___________________________________________________________
Mr. Shahid Akbar
Lecturer, Department of Computer Science, AWKUM

Chairman: ____________________________________________________________
Dr. Mukhtaj Khan
Chairman Department of Computer Science, AWKUM.

1
Declaration of Originality

I hereby declare that this software, neither as a whole nor as a part there of has been copied out

from any source. It is further declared that I developed this software and this report entirely on the

basis of our personal efforts made under the sincere guidance of my project supervisor.

If any part of this software proved to be copied or found to be a report of some other, I shall standby

the consequences. No portion of the work presented in this report has been submitted in support

any application from any other degree of qualification of his or any other university or institute of

learning. I further declare that this software and all associated documents, reports and records are

submitted as partial requirement for the degree of BCS (SOFT). I understand and transfer

copyrights for these materials to ABDUL WALI KHAN UNIVERITY MARDAN. I shall not sale

this software and documents not get any financial gains from these.

Date: _____________

Signature: _______________________
Amir Taimour Shah
Reg No: 14-F-AWKUM-USM-BCS-SOFT-09

2
Certificate from Supervisor
It is certified that Mr. Amir Taimour Shah Reg No: 14-F-AWKUM-USM-BCS-SOFT-09. Has

carried out all the work related to this project report under my supervision at the department of

Computer Science, Abdul Wali Khan University, Mardan.

Supervisor:
___________________________

Mr. Shahid Akbar (Lecturer)

Abdul Wali Khan University, Mardan

3
Dedication

The Prophet of Mercy (Peace Be Upon Him), Islamic Republic of Pakistan and to our

honourable parents, teachers and friends whose support have given me the strength determination

and fortitude to accomplish my goal. They are assets of my life.

4
Acknowledgement

First and foremost I would like to thank Almighty ALLAH, my Father for having empowered

me with the knowledge and understanding to successfully complete my degree with such

invaluable joy and experience.

Special thanks to my supervisor Mr. Shahid Akbar for his continuous support during my

project, for his patience, motivation and immense knowledge. His guidance has helped me

throughout my research and I could not have imagined having better advisor and mentor for my

bachelor study.

5
TABLE OF CONTENTS
Abstract........................................................................................................................................................ 8
CHAPTER No 1. ......................................................................................................................................... 8
1. INTRODUCTION: ................................................................................................................ 9
2. PROBLEM STATEMENT: ................................................................................................. 12
3. THE GOALS OF THIS PROJECT:.................................................................................... 13
4. GAME DESIGN: ................................................................................................................... 13
CHAPTER 2 .............................................................................................................................................. 15
1. UNITY 3D GAME ENGINE: ............................................................................................... 15
2. THE SCENE VIEW: ............................................................................................................. 15
3. THE GAME VIEW:.............................................................................................................. 15
4. THE HIERARCHY VIEW: ................................................................................................. 15
5. THE PROJECT VIEW: ....................................................................................................... 16
6. THE INSPECTOR VIEW: ................................................................................................... 16
CHAPTER 3 .............................................................................................................................................. 17
1. THE PHYSIC ENGINE: ...................................................................................................... 17
2. SYSTEM REQUIREMENTS: ............................................................................................. 18
3. FUNCTIONAL REQUIREMENTS: ................................................................................... 18
4. NON FUNCTIONAL REQUIREMENTS: ......................................................................... 18
5. USE CASE: ............................................................................................................................ 19
6. LOGICAL DESIGN: ............................................................................................................ 19
7. FLOW CHART: .................................................................................................................... 19
CHAPTER 4 ............................................................................................................................................. 19
1. SETTING THE SCENE: ........................................................................................................... 20
2. CONTROLLING THE P LAYER’S CAR: .................................................................................. 20
3. MOVING F ORWARD: ............................................................................................................. 21
4. MOVING LEFT AND RIGHT: ................................................................................................. 22
5. AN INTRODUCTION TO VARIABLES : ................................................................................... 24
CHAPTER 5 .............................................................................................................................................. 26
1. BASIC PHYSIC: ................................................................................................................... 26
2. ADVANCED PHYSCIS: ...................................................................................................... 28

6
TABLE OF CONTENTS
3. THE GAME CAMERA: ....................................................................................................... 30
4. BASIC CAMERA: ................................................................................................................ 30
5. SMOOTH CAMERA: ........................................................................................................... 32
6. THE OTHER CARS AND AI: ............................................................................................. 33
CHAPTER 6………………………………...............................................................................................39
1. FINSIHING RACE LEVEL: ............................................................................................... 38
2. FUTURE UNITY FEATURE: ............................................................................................. 38
3. THE GAMECONTROLLER: ............................................................................................. 42
4. HIGH SCORES: .................................................................................................................... 47
CHAPTER 7 .............................................................................................................................................. 50
CONCLUSION: ........................................................................................................................................ 52
REFRENCES: ........................................................................................................................................... 53

7
Abstract

Atgameplay scenario can be defined as a series of eventstthat emerge from a given context. These
eventstcan potentially be influenced by thetplayer through gameplay, which results in meaningful
interactiontwith the simulation. Creating gameplay scenarios in computertgames and training
simulators is an immensely expensivetand time consuming undertaking. A common trait fortmost
scenarios created is that they tend totbe static. Once a player has completed thetscenario once, he
knows exactly how it will behave thetnext time, reducing or removing thetreplay value of the
gameplay scenario.tThis thesis investigates how artificial intelligencettechniques can be used to
definetvirtual worlds and interaction between entities,tsuch as virtual humans, to dynamically
generatetgameplay scenarios by simulating the conflicttbetween entities as they clash over
conflictingtinterests in the world. The firsttpart of this thesis introduces thetvast field of artificial
intelligence, howtit is usually applied in games,tand how new concepts are slowly trickling into
thetfield of game artificial intelligence.tTopics introduced include crowd simulation techniques,
agenttsimulation and how one can describe arbitrarytvirtual worlds through the use of semantics,
smarttobjects and fuzzy logic. The second parttdescribes the practicalities of the implementation.
Here,tthe game engine used to develop the prototype gametworld is presented and compared to
othertalternatives. The design allows for quickly defining the important resources, actions,tand
potential interactions between entitiestin a virtual world. Finally, the implementation cantbe run
as an add-on to a virtual world,twhich can be used to drive scenario generation through conflict
simulation.tThe work presented in this thesis provides atproof of concept solution for
dynamicallytgenerating gameplay scenarios. By providing game developers with a pattern for
definingtthe elements of their virtual world that is the source oftconflict, the “Faction interaction
framework”tprovides an approach to have the virtual worldtautonomously generate myriads of
gameplay scenarios depending ontuser input. This has potential application especially totlarge,
open world games,tmassively multiplayer online games and training simulators, wheretthe
generation of novel gameplay scenarios is challenging duetto the large amount required.

8
CHAPTERtNo 1.

1. INTRODUCTION:

The topic of this thesis is gametdevelopmenttwith Unity, game production, gametmechanics and
the effects of gaming. Unityt3Dtgametenginetwastusedtduringtthistprojecttastit has the
capabilitiestthe group needed for deploying the gametmade to as manytmobile devicestas possible.
Unitytcan deploy thetgame made to Windows,tUNIX,tMac,tiOS, Android and Windows
8tphone.tAs this istthe only game engine out currently thattcan deploy to all these operating
systemstat once Unity was the choice for thistproject. There is a multitude of reasons behind the
motivetfor this research. One of the reason is, the gametindustry in world is becoming quite large
due to several populartgames released by different companies and this alone would be enough
encouragement totlearn game development techniques using Unity. This thesistbegins with
explaining Unity game engine and the graphical usertinterface used to produce the games. The
thesis will thentgo into the mechanics of eachtgame and some of the code thattthe games use. The
programming language usedtfor the games is C#, specifically fortscripting in the games. The thesis
willtalso cover deploying the game totmultiple platforms and mobile devices.

The ideatbehind this second project is to providetusers the opportunity to create atfull, working
game. This is a more advanced projecttand will focus more on the generaltconcepts of
programming and scripting atcomplete game within the Unity environment.tIt will introduce you
to advanced physicstand modeling, camera views andtstyles that work for the racing genre, the
basicstof opponents AI, triggers,tsetting up more complex GUIs forta game, scoring and end-game
goals.tThis project assumes that you have atdecent familiarity with the Unity interface and
workflow,tand also some familiarity with the firsttproject, as we are going to skip some basic
conceptstto quickly get in-depth into the game.

Thetproject will lead you through atseries of steps that will build on onetanother, with detailed
explanations so thattyou have an excellent working knowledge of the technicaltaspects of the
finished Racing game.tThere will also be some detailed explanationstof basic programming
questions and concepts.tWhen complete, you will be able to taketaway scripts and techniques
applicabletto many other types of games that cantbe used in your own projects.

9
Thesestscripts include such things as: player car/objecttscripts, camera scripts, enemy and
AItscripts, goal trigger scripts, creating waypoints, timertscripts, and game startup and
GUItscripts.tBecause of the complexity of this project, it willtbe broken down into severaltmain
sections, some oftwhich will have a number oftspecific subsections.

Developingtsoftware applications is a time-consuming process,tand with time-consuming


processes come high costs.tDuring the last years, several software development
methodologies,toften known as agile software development,thave become widely used by
softwaretdevelopers to address this issue.tMany different development methodologies cantbe more
or less good, dependingtof the task and application type.tOne of the software development
methodologiestis the evolutionary software method,twhich, as the name hints,ttakes on an
evolutionarytapproach to the problem, and allowstthe project to evolve through different stagestof
the project. Ourtcase study will show how well thistevolutionary approach worked on our project
wheretwe choose to develop a 3D graphic computer game.tSome requirements for the computer
game were given fromtthe beginning, such as:t3Dtgraphicst– The game must containt3D models,
andtrender these in the game.t3D environments were never atrequirement, and platform games
with 2Dtenvironment could still open up for 3D objects.tThe game result must impress whoever
plays the game.tIt should last long, and make the players come back andtplay it over and over
again.tTo achieve an impressive result, wetwould need to add modern graphical effects,tsuch as
real-time rendered soft shadows,tmotion blur, and ambient occlusion.tWorking with these
requirements, we decided to usetUnity as our platform to develop our 3Dtgame with. This decision
wastmade with regard to that the platformthad many in-built tools and provided a good framework
fortus to get started with the development astfast as possible. Thetfact that Unity game engine
alsotused C# as development language was also in consideration, sincetwe wanted to learn this
newlytdeveloped C-based object-oriented language. The requirementtfor the game to contain 3D
graphics introduced an interestingtchallenge for the project group,tsince all had none or little
experiencetin 3D modelling.tSpending time learning how to modeltproper 3D models for our
gametwas therefore necessary. During the researchtto find out what 3D modellingtprogram to
use,twe found that we could usetdifferent studios to create modelstthat we could later import totour
game project. Unitytdoes a lot of things for you-UI,tsound, lighting, physics, etc.tUnity is
comprised of many frameworks and engines like NVIDIA PhysX,twhich is a physics
engine.tNVIDIA PhysX handles a lot of stuff,tjust like Unity - fluid dynamics,tvehicular motion,

10
etc. Unity is a game engine.tIt is a collection of librariestthat are built and linked togethertto make
games work (graphics,tphysics, input, network, etc) and are accessible via an unified API.

WhiletUnity itself is the engine,tthe way you write code for yourtgames is tied with thetincluded
framework (like inheriting from MonoBehaviour) to simplify thetgame development down to what
you really need to code.tUnity gives users the ability to create games in both 2D and 3D,tand the
engine offers atprimary scripting API in C#,tfor both the Unity editor in the form of plugins,tand
games themselves, as well as drag and drop functionality.tPrior to C#tbeing the primary
programming languagetused for the engine,tit previously supported Boo,twhich was removed in
the Unity 5 release,tand a version of JavaScript called UnityScript,twhich was deprecated in
August 2017tafter the release of Unity 2017.1tin favor of C#.

The engine hastsupport for the following graphics APIs: Direct3Dton Windows and Xbox
One;tOpenGL on Linux, macOS,tand Windows; OpenGL ES on Android and iOS;tWebGL on the
web; and proprietary APIs on the video game consoles.tAdditionally, Unity supports the low-level
APIs Metal ontiOS and macOS and Vulkan on Android,tLinux, and Windows, astwell as Direct3D
12 on Windows and Xbox One.

Withint2D games, Unitytallows importation of sprites andtan advanced 2D world renderer.tFor


3D games, Unity allowstspecification of texture compression, mipmaps, andtresolution settings
for each platform thattthe game engine supports, andtprovides support for bump
mapping,treflection mapping, parallax mapping,tscreen space ambient occlusion
(SSAO),tdynamic shadows using shadow maps,trender-to-texture and full-screen post-processing
effects.

Sincetabout 2016 Unity also offers cloud-basedtservices to developers, these are presently:tUnity
Ads, Unity Analytics,tUnity Certification, Unity Cloud Build,tUnity Everyplay, Unity IAP ("In
app purchase" -tfor the Apple and Googletapp stores), UnitytMultiplayer, Unity Performance
Reporting,tUnity Collaborate and Unity Hub.

Unitytsupports the creation of custom vertexes,tfragments (or pixels),ttessellation, compute


shaders and Unity's own surface shaders using Cg,ta modified version of Microsoft's High-Level
Shading Languagetdeveloped by Nvidia.

11
2. PROBLEMtSTATEMENT:

Intthis thesis,twe address the challenge of automatically generating virtualtworld scenarios


through faction-interaction modeling.tThis includes seeking solutions to questions like:tHow can
one generate gameplaytscenarios by simulating thetinteractions between the agents that populate
a game world,twhile still allowing for scripted events to drive narrative?tScripted scenarios in
gamesttend to offer a highertquality of linear narrative and gameplaytthan can be
generatedtthrough procedural systems.tA scenario in a virtual world cantbe described as the
contexttin which the game takes place,tthe development of the game over time,tand some events
that take place during game play.tCreating scenarios is a painstaking process,tand the design of
such content intlarge quantities is immensely expensive. Despitetthe cost of scripted content,tit
offers littletto no replay value.tWhile this might be finetfor entertainment products with a one-time
fee,tit is less beneficial for subscription based gamestand training simulations where new and
different challenges are essential.tAn additional issue is also posedtin that such systems are
usuallytlarger in scope than one-time fee gamestwhich require considerations to betmade in
regards to scalability.

Totreach our purpose of achieving a completetmarketable racing game,twe need to focus on these
three areas:

1.tGame design - Designing a game that is competitive might be the most difficult process in
development as we need our design to be unique in order to let the game stand out from its
competition.

2. Graphics - Graphicstis seen as an important parttof video games by many sincetit provides a
pleasant visual experience.tGreat and realistic graphics can achieve this,tbut they also demand a
lottof computational power which couldtprove problematic, since the game hastto run smoothly.

3.tPhysics - Our game is set in space, antenvironment everyday people have no realtperception
of. Creating physics that simulatetan intuitive feeling of space withouttcompromising the player’s
abilitytto control can be difficult.

12
3. THE GOALS OF THIS PROJECT:

This project wastintended to be a script projecttthat really focuses solely on scripting;tit is meant
to be antintroductory project on scripting in Unity for beginners.tFor this reason, the modelstare
kept as simple as possible,tand in the scripts we chosetto use the simplest possible solutionstto get
a functional game.tThe car, for exampletcan be tweaked much more thantwe did in the
project.tThis project is not meant totcreate a fun game,tbut rather it is meant as atscripting project
to showtthe complete process of creatingta game from the scripting side.tOur aim was to focus on
thetfollowing areas:

 Totexamine how video games are designedtand to see how different game
mechanicstwork and how to use them in the development of atgame.
 To setup the requirements fortthe development of 3D racing car game.tA car game is
simpletand fun to play making ittavailable to anyone.
 Totshow how a few of these gamestwere made in Unity and also deployedtto several
different devices and operating systems.t
 Furthertthe thesis shows how deployment to severaltmobile devices helped to allow
userstof all ages and backgrounds to betable to test the games.t
 Giving the programming group insighttand ideas for improvements to the gamestbeing
produced.

4. GAME DESIGN:

Game Design and Concepts Intthis project, we were left free totdecide what type of game we
wanted to develop.tThe initial concept was to developta racing game. However, there werettwo
different racing game ideas,twhich will be described below.tIn compliance with our development
process,tthe game concept evolved,tas more and more features weretadded. To further explain how
thetgame concept evolved,tthe development has been divided into three parts.t2.1.1. Initial
Concept Ourtfirst concept had a game play similartto Remedy’s game in 1996,tcalled Death Rally1

13
,twhere each player had a cartequipped with a weapon, andtthe goal was to hunt downtthe
opponent’s cars.tThe other idea was to createta simple race track wheretplayers could collect coins
in order to win.tSince the first idea involved muchtgreater work than the latter one,tit was decided
that thetfirst idea were to be given a low priority,twhereas the second were to betgiven a high
priority.tSecond Iteration we decided that a jointtsolution would be best,twhere players are able to
collect coinstand then use the money to make upgrades.tThese upgrades would be similar to the
concept of levelling,tsomething that many players appreciate. It wastalso decided that the racing
tracktshould be a garage orta store-house, filled with containers,tboxes, and miscellaneous objects
suitable fortthat environment. Since driving a realtcar around a garage is virtually impossible,tit
was decided that we should maketremote controlled cars instead. The final ConcepttWe kept most
of the ideastfrom the second iteration with onetexception for the death rally concept.tIt appeared
that our first instinct,tto give this idea a low priority,twas right and in this last iteration,tthe idea
was dropped. However,ta racing game where players onlytmay collect coins and nothing
more,tsounded a bit boring. Influencedtby games like Super Mario Kart,tit was decided that power-
upstshould be added. There are a numbertof different power-ups, and theytcould be divided into
two groups;tthose that affect the car thatthit the power-up, and thosetthat affect the
opponents’tcars. A more profound descriptiontof the different power-ups follows.tIn addition to
the othertimprovements, one change was madetto the points system.tIt should be possible to collect
threettypes of coins,tworth 50, 100 and 200tpoints.

14
CHAPTER 2

1. UNITY 3D GAME ENGINE:

Unity 3D is a game engine and complete integrated developmenttenvironment (IDE) with an


integrated editor,tasset workflow, scene builder, scripting,tnetworking and more. It also hasta vast
community and forum wheretany person wanting to know andtlearn to use Unity can gotand have
all their questions answered.tThere are five main views used intthe Unity editor to get alltthe work
done, the project view,tscene view, game view, hierarchy viewtand inspector view,tall of which
aretexplained in more detail below.

2. THE SCENE VIEW:

The scene view is onetof the most used views astthis is where all the gametobjects are placed and
scenes fortthe game are built.

3. THE GAME VIEW:

The game view is whattuser will see when the gametis started. There are several optionsfor this
window.tAcross the top of the windowtthere are several button/drop down

Menustwhich can change things from thetperspective, full screen, and gizmostshown in the game
view.

FIG 1.1 THE GAME VIEW

4. THE HIERARCHY VIEW:

The hierarchy view istwhere all the objects in the gametcan be created, accessed, groupedtand
manipulated to make thetgame. When the project is saved,tthe objects are saved in atscene file.

FIG 1.2 THE HIERARCHY VIEW

15
5. THE PROJECT VIEW:

The project view is wheretall the scripts and scenes aretaccessible from. This view is exactlytlike
the file explorer on Windowstor Mac and allows creating filestand folders to help organize
thetprojects assets. The left panel oftthe browser shows the folder structuretof the project as a
hierarchical list.tWhen a folder is selected fromtthe list by clicking, itstcontents will be shown in
thetpanel to the right.tYou can click the smallttriangle to expand or collapse thetfolder, displaying
any nested folderstit contains. Hold down Alt whiletyou click to expand or collapsetany nested
folders recursively.

Thetindividual assets are shown in thetright hand panel as icons thattindicate their type (script,
material,tsub-folder, etc). The icons can betresized using the slider at thetbottom of the panel;
theytwill be replaced by a hierarchicaltlist view if the slider istmoved to the extreme left.tThe space
to the left oftthe slider shows the currentlytselected item, including a full pathtto the item if a
searchtis being performed.

FIG 1.3 THE PROJECT VIEW

6. THE INSPECTOR VIEW:

The inspector view is wheretall the physics and properties oftthe objects are stored and
accessedtfrom. Every game object has attransform; this is what holds propertiestof the object such
as rotation,tposition and scale. Other propertiestare the physics affecting the object,ttextures to
load on the objecttand sound. se thetInspector to view and edit thetproperties and settings of almost
everythingtin the Unity Editor, includingtphysical game items such as GameObjects,tAssets, and
Materials, as well as in-Editortsettings and preferences.

16
CHAPTER 3
1. THE PHYSIC ENGINE:

Unity contains the powerful NVIDIA®tPhysX® Physics Engine. With this physic engine thattis
built into Unity many powerfultthings can be added to a game.tBelow is a list of several of
thetfeatures usable in Unity

tInteractive cloth

 Dedicated wheel collider

tRagdoll wizard

 Hingest

 Springs

tCharactertlimbs

 Fully customizable configurabletjoints.

 Soft bodies (like atdeflated beach ball)

 Ridged bodyt(which receives forces and torque totmake the objects move in a realistictway with
notscripting required.)

The physics engine is atgreat asset with all these features alreadytbuilt in. Without this a
gametprogrammer would need to create their own physicstengine. Making a physics engine is
antentire project in itself.tUnity is truly an all-in-one game engine designedtto create the next great
game.t

Everytgame made during the thesis projecttuses some elements of this physic engine.tFor collision
detection attleast one of the two objectstcolliding needs a rigid body added to it.tThe blocks and
balltin brick breaker use thetridged body so that they cantuse to force of gravity totfall or stay on
thetfloor of the level. Physicstis a very important part inta game that is being designedttoday.

17
2. SYSTEM REQUIREMENTS:

ThetSystem Requirements Specification document describestall data, functional and non-


functionaltrequirements of the software under developmenttor production. It also defines whatta
system is supposed to accomplish.tTo be used efficiently, all computertsoftware needs certain
hardwaretcomponents or other software resourcestto be present on atcomputer. These prerequisites
are known ast(computer) system requirements and are oftentused as a guideline as opposedtto an
absolute rule.tMost software defines two sets oftsystem requirements: minimum and
recommended.tWith increasing demand for higher processingtpower and resources in newer
versionstof software, system requirements tend totincrease over time. Industry analyststsuggest
that this trend plays a biggertpart in driving upgrades to existingtcomputer systems than
technological advancements.

3. FUNCTIONAL REQUIREMENTS:

Atfunctional requirement defines a functiontof a system or its component.tA function is described


as atset inputs, behavior, and outputs.tOur game functional requirement istopen the game which
takestless time to move at main menu.tWhen click on play button it goestto the main level whichtis
named by leveltone. A sound is having atchoice whether play on or playtoff in player character,
enemytcharacter, shoot firing guntetc.

4. NON FUNCTIONAL REQUIREMENTS:

A non-functional requirementtis a requirement that specifies criteria thattcan be used to judge the
operationtof a system, rather than specific behaviors.tThey are contrasted with functional
requirementstthat define specific behavior or functions.tThe plan for implementing functional
requirementstis detailed in the system design.tThe plan for implementing non-functional
requirements istdetailed in the system architecture,tbecause they are usually Architecturally
SignificanttRequirements. It concerns as the othertfunctionality about a system.

18
5. USE CASE:

A use case ista list of actions or eventtsteps typically defining the interactions betweenta role
(known in the Unified ModelingtLanguage as an actor) andta system to achieve a goal.tThe actor
can be athuman or other external system.

6. LOGICAL DESIGN:

Thetlogical design of a system pertains totan abstract representation of the data flows,tinputs and
outputs of the system.tThis is often conducted viatmodeling, using an over-abstractt(and
sometimes graphical) model of thetactual system. In the context of systems,tdesigns are
included.tLogical design includes entity-relationship diagramst(ER diagrams).

FIG 1.4 LOGICAL DESIGN DIAGRAM

7. FLOWCHART:

Graphictrepresentation shows a sequence of activities,thow system should be done a worktin a


particular flow.tIt is ladders of sequences totcomplete process of execution. Fortgaming
application, a flowtchart diagram defines a series of stepsta process must execute consistently.tA
flow char diagram showsthow tasks will flow between resources andtpermit the sequence to
moveton.

FIG 1.5 FLOW CHART

19
CHAPTER 4
1. SETTING THE SCENE:

In this section, we’re going totquickly set up the physical objectstand assets that will be necessary
in our racingtgame. These include the players and enemytcars, the racing track, scripts for eachtof
the project sections, andtpre-made scenes that explain the project’stconcepts. We’ll start by
downloading thetpre-made assets and creating our projecttby opening them.

Begintby downloading the Project Asset filestand then unzipping the files to createtthe
"car_project" and "car_project_complete" projecttfolders. Both folders contain all of thetrequired
assets for the projecttseparated into logically arranged subfolders.

Movetthese folders where you prefer on your hardtdrive and then open Unity.tSelect File -> Open
Projecttand locate and open the "car_project" project.tUnity will restart, update the assets,tand then
open the standard project game world.tOpen the Basic Setup scene.tWe’ll make two minor
modifications nowtby changing a couple of thetvalues in Edit -> Project Settingst-> Player.
Change the Default Size oftthe build to 800x600, and changetthe Default Graphics Quality to 4
(1024tx 768 is now the defaulttsetting for new projects). We’lltuse the provided assets ([A]tCar
Control through [D] Game Setup)tto work our way through the sectionstand concepts in the
project.tAt the end of the project,twe will have learned enough to create atsmall series of complete
scenes that incorporate alltof the project concepts,tand create a complete racing game.tTo begin,
we’ve opened the Basic Setuptscene and will start work on thetfirst working section.

2. CONTROLLING THE PLAYER’S CAR:

This is the longest section of the project,tso it’s been broken into fivetmajor subsections. Each of
the subsections buildstupon the knowledge learned in thetprevious subsection so that at thetend of
Section III, you’ll haveta thorough knowledge of many important aspectstof Unity and will have
saved severaltscenes of your work.

Controllingta player’s car in a game requirestan understanding of physics in game engines,twith a


main focus on motion ofta vehicle, over time, through a specifictgame world. It also involves the

20
mechanicstof collisions (and collision detection), andtwill introduce the concept oftvariables that
willtbe required for this sort of playertcontrol of objects.

ManytUnity users will be familiar with muchtof what is discussed in this section.tThis section will
provide a complete understanding oftall of these concepts to thetbeginning user and, for the
advanced user,tI hope to illustrate how Unity uniquelythandles all of these physical
andtmechanical concepts, so that they can betused as a basis and help youtdevelop your own titles.

We’lltstart with the very basics in thetfirst subsection – moving a player’stcar forward through the
world.

3. MOVING FORWARD :

Objects inta scene are moved by usingt"Transform" and an "Update" function that ist"called"
(runs) every frame.tTransforms take care of alltthe movement of every object in Unity.tBefore we
get to the code,tlet’s review some very basic codingtstuff.

A function is a piece of JavaScripttcode that is defined once, buttthen can be called many times by
thetprogram. A JavaScript function can be passedtparameters that specify the values thatta function
will operate on.tFunctions can also return values backtto the program. Functions aretdefined in
JavaScript liketthis:

Once a function is defined you cantinvoke it by following the function’s nametwith an optional
comma-separatetlist of arguments within parentheses. Thetfollowing four lines of code
wouldtprint the number 9 totthe console:

Sometfunctions are automatically called ontcertain events. An important and verytuseful function
in Unity thattis called every frame istthe "Update" function.

To do anything interestingtin your game, you’ll have totcall some of Unity’s built in functions.tA
few paragraphs ago Itmentioned that objects in a scene aretmoved by using the classt"Transform"

21
and an "Update" functiontthat is called every frame.tTransforms take care of all the movementtof
every objecttin Unity. A complete list oftall function’s supported by Transformtcan be found
online.

To callta function on an object,tyou refer to the object,tfollowed by a period and the functiontto
call. In the following example,twe call the Transform’s Translate function.tIt has 3 parameters that
are used totdefine how much to transform (move) antobject along it’s x, y and ztaxis.

In the project, this is the MoveForward.jstscript in the [A] Car Controlt-> 1 Move Forward folder,
andthas the comment line at the beginningtto remind us and anyone elsetwho looks at our code
whattthis does (see the You Comment,tRight? note at left). Attach this script totthe Player Car
object using drag and droptso that the car will simply movetforward one unit along it’s z axisteach
frame. The z axis istthe blue arrow when you select thetcar. Run your scene to seetthis script in
action. Dota Save as... and save the scene as MovetForward in the 1 Move Forward. Playtwith the
values of the scripttto make the car go uptor sideways instead of forward,tor to go faster forward.

4. MOVING LEFT AND RIGHT:

We’re now going to usetTransform and Input to move the cartleft and right. Open up the Basic
Setuptscene again and attach the [A]tCar Control -> 2 Move and Turnt-> MoveAndTurn.js script
to the PlayertCar. Run the scene and usetthe arrow keys to move the playertcar. The motion istvery
simplistic but we’re nowtusing input from the player totmodify an object within the game
world.tHere’s the code (MoveAndTurn.js) that’s makingtthis happen:

We’re still using the Updatetfunction to make the car move,tbut only every frame it receivestplayer
input. Instead of declaring atnumber of units to move along eithertthe z or y axis astin our first
section, we’re using atnew function to make movement happen:

22
Input.GetAxis;tand one new function called transform. Rotatetto make the car turn.tThese are basic
movement functions intUnity.

Input.GetAxis is a function that lookstfor mouse or keyboard input fromtthe user and who’s values
range from 1tto -1 (for keyboard). You cantchange many of the settings/variables associated with
thetInput.GetAxis using the Edit -> Project Settingst-> Input menu and find moretinformation in
the online scripttreference documentation.

transform.Rotate is similar to transform.Translate, except thattinstead of moving ("translating") an


objecttalong an axis, it rotates the objecttaround the specified axis. In our example,tit will continue
to rotate thetobject around the specified axis astlong as one of the "Horizontal" inputtkeys (the left
and right arrows)tare held down.

I mentioned thattthe motion of the player car iststill simplistic. But before we add sometmore
physics to the car’s motion,tI want to review to concept oftvariables in Unity. Save as... and save
this completedtscene in 2 Move AndtTurn as Move Forward.

FrameratetIndependent Movement I would like to taketa second to go off trackt(pardon the pun)
here for a fewtminutes and talk about something calledt"framerate indepedent movement." Notice
how oldtcomputer games play really quickly ontyour new computer? Or how onetframe of game
action can taketa different amount of time depending onthow much motion or how
manytexplosions were taking place? That’s thetresult of framerate dependent movement.

Intthe above code, we move antobject 1m along its z axis pertframe, but this will move thetobject
a different distance along thetz axis per second on different machines.tTo work around this issue,
you will most alwaystwant to change values dependent on time.tIn our simple example, you want
totmove a car 1 meter per second.tIn code this translates to:

23
Time.deltaTimetis the amount of time thetlast frame took. By multiplying withtTime.deltaTime,
you make your objects movet1 meter per second instead of 1tmeter per frame. When shouldtyou
multiply by Time.deltaTime? You wanttto multiply by delta time when continuouslytchanging a
value every frame. Mosttof the time this is when dealingtwith input, as shown in the followingttwo
simple code examples:

Theretis one notable exception when dealingtwith input: Mouse delta, which is alwaystabsolute.
It is how far the mouse moved.tThus you should not multiply by delta time.tA simple code example
of this is shown below:

Intthe next subsection, An Introduction TotVariables, we have applied thistknowledge about


framerate independenttmovement.

5. AN INTRODUCTION TO VARIABLES:

Many Unitytusers have some programming experience andtwill be able to simply skimtthis
section. But sincetthis project has been designedtas an introduction to Unity’s
programmingtfunctionality, we should explore a cornerstonetof computer programming known as
variablestfor newer users. The concept oftvariables will come into play intthe next section of the
projecttwhen I will add some advancedtphysics and behvaiours to thetplayer’s car.

At its most basic, variablestare used to store and manipulate data.tA variable has a unique name
andtstores a value (numeric, text etc) thattcan be used by the program totdo something.

The first line of code intthe following example creates a variabletnamed "i" and assigns the value
"3"tto it, while the second line of code createsta variable named "sum" whosetvalue is equal to our
firsttvariable "i" multiplied by "2".tIn this case, "sum" wouldtbe equal to "6".

24
Variables also havetsomething called "scope;" most easily understoodtas being the area oftyour
program in which it istdefined and used. A "public" variabletis defined outside any functionstand
available for use everywheretinside of a script, while at"local" variable is defined only insideta
specific function where ittis created, as shownthere:

Any public variablestin your script will show uptin the inspector when you attachta script to a
game object.tIn the inspector you can thentchange the value. How istthis important? The value that
istshowing in the Inspector can betchanged in the Inspector and overridestthe value used in the
script.tThis meanstthat

doesn’t always print 5, becausetyou can changetthe value of i intthe Inspector to sayt7.

We can summarize what we nowtknow about variables so fartby way of a short exampletscript
(shown below): playerLivestis a public variable,twhile carSpeed is a localtvariable.

6. MOVING LEFT AND RIGHT (WITH VARIABLES):

Open up thetBasic Setup scene again andtattach the [A] Car Controlt-> 3 Variables ->
Variables.jstscript to the Player Car.tRun the scene and use thetarrow keys to move the player car.

Thetmotion has now dramatically changed when comparedtto the previous scene. It’stnow the
Variables.js script in thistasset folder making the player’s cartmove. Here it is in detail:

25
Noticetthat var speed = 10.0; and vartrotationSpeed = 100.0; are public variablestthat are outside
the functions and willtappear, and can be edited, intthe Inspector panel. Feel free totexperiment
with them.

The script makestuse of everything we discussed intthe Introduction to Variables section.tThe


player car now slowstgradually after the player stopstholding the arrow keys. Thistis a bit weird at
firsttbecause our code actually justtmoves the car forward withta constant velocity. But
thetInput.GetAxis function automaticallytsmoothest keyboard input and becausetwe multiply the
input withtvelocity the velocitytis automatically smoothed. Youtcan modify the smoothness of
keyboardtinput, setup joysticks etc.tvia the input manager. Editt-> Project Settings ->. Withtthese
basic in mind, wetcan now bring other physicstinto our racing game;tspecifically, RigidBody and
Colliders

CHAPTER 5

1. BASIC PHYSIC:

Intthis scene, we want to starttto affect the player’s car throughtthe use of forces and torques
(angulartforces) rather than position andtrotation directly. This hastseveral advantages including
more realistic motion,tbut more importantly, wetdon’t have to multiply movements
bytTime.deltaTime when working with physicstbecause forces are already time
independent.tOnce again, start by opening up thetBasic Setup scene, then click ont[A] Car Control
-> 4 Physicst-> SimplePhysics.js and examine it intthe Inspector panel.

ThetSimplePhysics.js script for thistis not any more complex thantthe script for MovingtLeft and
Right With Variables.

Intthis section we will buildtthe first version of atraycast car. A raycast car ista car which slides
overtthe ground. It’s wheels don’t spintas at drives forward; in this respecttit is actually more like
a snowmobiletthan a car. Every frame wetapply a force to move it forward.tIt doesn’t move
sideways becausetwe will use a Physic Materialtwith anisotropic friction. Anisotropic frictiontis a
necsssary part of atgame involving motion because it allowstyou to have different frictiontvalues

26
for forward or sideways motion.tWhen moving sideways we will useta much higher friction value
thantforward. This will make the carttend to slide forward instead of sidewaystand follow the front
wheels whentthey are rotated. We’lltuse a simple, three-step process totbuild the first versiontof a
raycast car for the playertto control.

First, we want to createtcolliders for the car: add a boxtcollider to the car_body of Player Car,tthen
add raycast colliders to each oftthe four wheels. These are addedtto an object by selecting
thetobject in the Scene view or thetHierarchy panel, and then selecting Component ->tDynamics
from the menubar. A raycasttcollider simply uses a ray fortcollision detection instead of a volume
shape;ti.e., a sphere. Also attach atRigidBody with a mass of 10 to thetPlayer Car. Second, create
atPhysic Material and set ittup as shown in the following screenshot.tRename it
WheelMaterialtand move it to the 4 Physicstdirectory. Assign this new material totall the 4 wheels
usingtdrag and drop.

27
FIG 1.6 BASIC PHYSIC SIMULATOR

You create a newtPhysic Material by clicking on thet"Create" button in your projecttpanel and
selecting Physic Material.tThese materials contain all thetfriction and bounciness parameters that
aretneeded to handle and enhance collisionstbetween objects. Physic Material also hasta setting to
combine/multiply theseteffects to increase these two forces.

Thetthird and final step is to attachtthe SimplePhysics script located in your Projecttpanel 4 Simple
Physics to the car.tIf you play with the value oftthe variables of the SimpletPhysics script in the
Inspector maketsure that Speed is at leastt100 and Rotation Speed istat least 80.

Wetcan now Run this scene and testtthe motion of our car.tSave the scene as Simple Physicstin
the 4 Simple Physics directory.

2. ADVANCED PHYSCIS:

In thistsection we’re going to improve thetray cast car. The main changetwe’ll make is that wetwill
now rotate the wheelstinstead of applying a torquetto the entire car totmake it rotate. Starttby
opening up the BasictSetup scene, and adding atbox collider, raycast colliders, andta RigidBody
to the various PlayertCar parts as we did in the previous section.tSave as... the scene now in the 5
MoretPhysics directory naming it simply Physics.

Nowtcreate and save two new Physic Materialst– one for the back wheel named BackWheel,tand
one for the front wheeltnamed Front Wheel. These will givetus more control over thetcar handling,
because we canttweak and fiddle with the friction valuestfor the front and back wheelstas separate
entities in thetInspector. Set these up using the valuestas shown in the smaller PhysictMaterials
setting screen shot intthe left sidebar on paget12.

Notice how we refinedtthe values we’ve assigned the Physic Materialstby adding a springy
contacttto the wheel’s physics materialtto make it soft. This istdone by enabling the usetSpring
flag, and setting springtto 25 and damper to 5.tFeel free to play around withtthese values to get the
damperstin your car right. We cantnow Run this scene and watchtthe improved motion of our car.

28
Nowtlet’s tackle the script associated with this scene:tPlayerCar.js. There’s two things in this
scripttthat will give the car better physicstin this section. 1) Intthe script we will now tweak
thetcenter of mass and inertia tensortso that the car has a lowertcenter of mass (to prevent ittfrom
flipping over too easily).t2) We remove the torque from thetcar because we’ll modify thetrotation
of the wheelstbased on the input horizontal axistinstead of torque.

When wetattach this script to the player car,tthe four declared variables will have totbe connected
in the Inspectortso that the script knows which variabletis associated with which wheelt(shown at
toptleft).

There aretseveral important parts to this script thattI will quickly review for the reader.

1.tThese are the four transform variables thattwe needed to connect to specifictwheels in the
Inspector panel..

2. This is wheretwe change the player car’s centertof mass based on our car model. Intour case,
the car is long and notttoo tall so we’ve moved thetcenter of mass slightly downtand toward the
front of the car.tThe center of mass is relative to thettransform’s origin. If youtdon’t set the center
oftmass from a script like wetare doing here, it will betcalculated automatically from alltcolliders
attached to the rigid body.tInertia Tensor Rotation and Inertia Tensortare the rotation of thetinertia
tensor and the diagonaltinertia tensor of mass relative to thetcenter of mass respectively.
Thetinertia tensor is rotated bytthe inertiaTensorRotation.

3. This function checks totsee if the car’s back wheels aretin contact with the ground/track
surface,tthen applies a relative force along the car’stz axis to move the car eithertforwards or
backwards based on the playertpushing the up or down arrows.tThis part also sets the angle oftthe
front wheels turning based on the player pressing thetleft or right (horizontal) keys.

4tand 5. These parts of thetscript track if the wheels are stilltin contact with the ground.tAt the end
of every frame we set hasBackWheelContact totfalse. OnCollisionStay is called everytframe if any
of the colliders oftthe car are colliding with othertobjects. Inside OnCollisionStay we check if the
collider ista backwheel. If it has, wetenable hasBackWheelContact again. Thistis all repeated every
frame,tthus hasBackWheelContact will track iftthe car is groundedtor not.

29
Now that we haveta fully functional player car, it’sttime for us to set up a cameratto follow the
player’s progresstin the race.

3. THE GAME CAMERA:

The goal of this shortertsection is to create and manage atcamera to follow the player’s car astit
races around the track. Inta racing game, one of the mosttcommon camera views is fromta third-
person perspective; thattis, behind and slightly abovetthe player. This projecttwill show you how
totcreate one of these cameras andtthen to move it along in atfluid manner with the player car.tIn
more advanced games you mighttwish to set up numerous cameras totcapture the action from
different angles.tThis more complex camera work is donetby enabling and disabling various
camerastbased on user input.

4. BASIC CAMERA:

Let’s start by first simplytgetting the main camera positioned abovetand behind the player
car.tOpen our previous scene’s Physics.unity scenetand do a Save as... int[B] Camera Control
Scripts -> 1tBasic Follow Camera and name thetfile Camera. Thistscene contains all of the
elementstand scripts from the previous sectiontof the project. Now attachtthe Camera.js script to
the main camera.

The Camera.jstscript has a distance and height variabletthat we will be able to modify fromtthe
Inspector, but also a "target" variable thattwe will need to assign to the player’s car.tConnect this
variable to the player cartobject the same way we connected thetwheel control variables to
thetwheel objects of the car object.

30
ThetCamera.js script is very simple.

1. We set up variables for height,tdistance and target.

2. We use the function LateUpdatetin this script to make sure that thistparticular script runs after
any other scriptstthat are run during atframe.

3. It gets the positiontand direction of the car to positiontitself.

31
4. It places itself a specifictdistance and height behind the target usingtvariables. In this instance
we’ve specified intthe script that behind means along thetnegative z-axis of the target. Thentwe
move the camera upwards bytheight, so the camera looks down ontthe car.

5. We rotate the camera totalways look at the target. Run the scene andtdrive the player car to see
the camera in action.tNeat!

But this is a very simple solution. Whattwe’d really like to see is the cameratreacting better to the
motion of thetplayer car. We need to createtand use a camera script thattsmoothes out the motion
of thetcamera as it follows the car.

5. SMOOTH CAMERA:

Start again by opening the Physics.unitytscene and do a Save as... in [B]tCamera Control Scripts -
> 2 Smooth Cameratand name the file Smooth Camera.tThis time, attach the SmoothtCamera
script to the main camera.tConnect the target variable to thetcar object as we didtin the previous
scene and Run the scenetto see the camera react moretsmoothly to the car’s movement.

What’stnow happening is that this cameratscript smoothes out rotation aroundtthe y-axis and
height, whiletstill maintaining a static horizontal distance.tThis method gives you a lottof control
over how the cameratbehaves because you can tweak lots of the variables.tFor every of those
smoothed values we calculateta wanted value and the current value.tThen we smooth it using the
Lerp function.

1.tWe set up variables for height,tdistance and additionally for damping.

2.tWe calculate both current and wanted rotationtand height for thetcamera.

3. We dampen the height and rotationtby using the Lerp function

(explainedtbelow).

4. We convert our rotation calculation fromtdegrees into radians so that thetQuaternion interface
understands it.

5. Intthis part we finally position thetcamera where we want it and pointtthe camera to always look
attthe target.

32
Run the scene and drive thetplayer car to see the improved camera intaction. Notice that we’re
using specifically the Mathf.LerpAngletto damp the rotation around the player car’stvertical (y)
axis, and using Mathf.Lerp totdamp the height. It also uses some othertbasic functions built into
Unity suchtas EulerAngles, Time.deltaTime and others. Mosttof the rest of the script uses basic
variablestand functions to move thetcamera withtthe car. It’s now timetto add opponent vehicles
andtprogram them to race around thettrack against the player. Otherwisetknown as the "cooltstuff."

6. THE OTHER CARS AND AI:

This section is where thetfun begins. Up until this pointtwe’ve been focusing on getting a cartunder
the control of the playertand also to set up a simpletcamera that will smoothly follow the cartalong
a race track.tBut this is a "racing" gamet– we certainly need some other carston the track that will
racetaround the course trying to beattus. It will be the most difficult totdate as the scripts in
thistsection are more advanced than anythingtwe’ve looked at so far,tmainly because we need to
createta method for opponent cars to drive themselvestaround the track. Totbegin the section we’ll
starttby creating a car that drivestitself around the race track.tThis car will be duplicated intthe
scene totcreate multiple opponenttcars.

7. AI CARS:

Start by opening the Physics.unitytscene and do a Save as... intCamera Control Scripts -> 1 AI Car
and Waypoints and nametthe file Waypoints. Create atnew Physic Material called AItCar Wheels
and set it up as shown attleft, then remove the previous wheel physictmaterials from the wheels in
thetInspector by replacing it with our newtAI Car Wheels material viata drag and drop.

Remove thetPlayercar script component from the AI Cartin the Inspector and attachtthe AICar
script, making sure to connecttthe four wheel variables to their associatedtwheel objects. Finally,
rename the player cartto AI Car. Save the scene attthis point.

In our AICar.js script we have the UpdateWithTargetPosition function which istthe meat of the
AICarScript. Ittrotates the wheels, accelerates forward andtslows down in sharp turns.tThe
UpdateWithTargetPosition function is called from insidetFixedUpdate. In FixedUpdate we also
calculatetwhere we should drive towards, andtcalculating where we drive towardstis simple.

33
We have a current waypointtas a target and we switch to the nexttwaypoint whenever we enter our
currenttwaypoint trigger. So we simply drivetan AI-controlled car towards the currenttwaypoint
and if we get close to the waypoint,twe let the car drive towards the waypoint after that.tThis
improves the AI car quite a bittbecause the car will otherwise have totdrive exactly through the
waypoint and will do sharp turnstshortly before hitting the waypoint trigger.

Withtthe basic in mind, we can nowtexamine the AICar.js script functions intdetail, like we did
with some of our previoustscripts.

34
There are several important functions of ourtAICar script that I will review in moretdetail for the
reader now.

1. Start. The Start function initializestthe center of mass. And also intializes thetactiveWaypoint
to the start waypoint.tThe active waypoint istused in FixedUpdate to find wheretwe want to drive
towards.

2A. Update With Target Position.tRotate the wheels towards thettarget. We use
transform.InverseTransformPoint to get the position relativetto the local coordinate system.tThen
we calculate thetangle using Atan2. Wetclamp the angle, because in real lifetwheels have a
maximum steeringtangle. Then we applytthe rotation to thetwheel transforms.

2B. If the wheel has contacttwe move thetcar forward. But that makestthe car drive over thetedge
way too much, so wetslow down if we have atlarge turning angle and aretdriving fast. We slow
thetAI car down by simply givingtthe rigidbody a high drag value.tThis is obviously not a very
realistictway of doing it, buttit is very easy and effectivetfor our purposes.

3. FixedUpdate. In FixedUpdate wettalk to the waypoint system to calculate thettarget position the
car should drive towardstthis frame. Then wetpass the target position ontotthe
UpdateWithTargetPosition function, whichtcarries out the movement oftthe car.

4. OnTriggerEnter. In OnTriggerEnter we register whentwe hit a new waypoint.tWhen we hit a


waypoint wetfirst check if it is the next waypointt– so that the player can’t skiptone waypoint or
gotbackwards – then make the active waypointtthe next waypoint.

5. OnCollisionStay. This function is thetsame as shown in points that calculates wheels


beingtgrounded.

With the AI car now functioning,tit’s time to look at setting uptand programming waypoints
aroundtour race track for thetcars to drive towards.

To set up waypointstyou add an empty game object totour scene, add a box collider to it, andtset
the isTrigger property to true,tthen attach the WayPoint script totit (this also draws the W
texturetlinked in the Gizmos folder).tThe waypoints need to betmanually connected by setting the
nexttvariable of every waypoint. The screenshottat left shows our completed tracktwith 30

35
waypoints set uptin the Scene view. Thetfirst waypoint on the track shouldtbe named "Start" in the
Inspector;tthe others should be calledt"Waypoint".

The waypoint script is used bytthe AI cars and is rather simple –tthe scripts contain a varible to
the next waypoint. Thistvariable needs to be setup manually intthe Inspector for every waypoint.

Static variablestare shared between all instances of the scripttand can also be accessed by other
scripts by using thetname of the script followed by atperiod and the function or variable name.

The static start variabletwas used by the car script totfind the first waypoint like this:
activeWayPoint = WayPoint.start;. Alsotthe game controller in the nexttchapter will use it to find
out whentwe cross the finish line.tLet’s look at the functions in thetwaypoint script.

1. CalculateTargetPosition. This function simply takes thetcurrent position of the car and returns
the point that thetcar should drive towards. This returns eithertthe position of the waypoint,tor the
next waypoint beyond that one if wetare close to the waypoint already.tThis is important so that
the car doesn’t drive exactly to thetcenter of the waypoint when ittdoesn’t exactly hit a waypoint
in the middle.

2.tAwake. This function initializes the starttvariable to the waypoint which has thetisStart flag set
in the inspector. We alsotdo error checking here to check iftall the next variables aretsetup.

3. OnDrawGizmos. This draws the waypointticon so waypoints are easilytpickable. Specific


information about Gizmos can betfound on OTEE’s scripting referencetsite.

4. OnDrawGizmoSelected. This function neatly draws thetline connecting one waypoint to the
next waypoint.tYou can select all waypoints totvisualize any setup errors that mighttexist in your
track in the Scene view.

36
Nowtthat we have the script written,twe can actually go about setting uptwaypoints on our track,
placing a test car intthe scene, and attaching the AICartscript to it to watch it drivetitself around
the track. In other words,tto set things up, you simply need to place a few waypoints in thetscene
– remember, one of them hastto have the isStart flag enabled, sotwe know where to start. All of
them have to betconnected together by setting the next property in thetInspector of each waypoint.
This scene usesta total of 30 waypoints.

Create duplicatestof the AI Car we assembled and place them in thetscene. Now Run the scene.
While thetscene Runs, our AI cars will simplytdrive towards the start waypoint.tWhen a car hits
it, the car will start drivingttowards the next waypoint in turn, andtthen keep driving from waypoint
to waypointtaround the track. To get ready for thetfinal chapter, Save this scenetin [D] Game Setup
-> 1 Finishing the Racingtlevel and name it Track1.unity.

FIGt1.7 MAP SIMULATIONS

37
This section is where we finishtthe game by adding some necessary thingstto polish the game.
These includetthings commonly found in many genrestof games and what we learn heretwill
certainly be applicable to your own gamestin the future. They includetthings like (race) timer, the
game’stgraphic user interface (GUI), texttobjects, a countdown timer, andtsimple scene
transitions. Let’s begin bytfinishing the racing parttof the project inta basic way

CHAPTER 6
1. FINSIHING RACE LEVEL:

Start by opening thetTrack1.unitytfile we savedtabove. This should contain fourtcopies of the AI


opponent car and our finished playertcar from the Physics.unity scene. We needtto add a script to
all of thetcars, both player and AI, thatttracks the cars as they drive throughtthe correct waypoints
(CarStats.js). And wetneed to create a simple text objecttthat will display a countdown to begin
thetrace by using a simple script (StartGame.js).

2. FUTURE UNITY FEATURE:

Version 1.2 of Unity should introduce dedicated wheel components that will allow for very
realistic cars.

Createta text object by selecting GameObject -> CreatetOther -> Text in the menubartand position
and scale ittso it is in the centretof the screen. You can leavetthe default texttit is displaying or
deletetit to leave it blank,tin the Inspector, oncetyou are happy withtit’s position and scale.tAttach
the StartGame.js scripttto the text object.

The camera will always displaytthe Text object in fronttof all other objects intthe game because
the cameratcontains a GUILayer component. The camera’stGUILayer displays objects that haveta
GUIText component and GUITexturestalways in the front specificallytto make interfaces
fortgames. Text objects haveta GUIText component included, visibletin the Inspector paneltby
default. GUI objectstremain in the sametposition in relation totthe camera even iftwe move the
cameratbecause they are, for altintents and purposes, attachedtto the camera.

38
The StartGame.js scripttis used to temporarily disabletall the cars in thetrace until a "ready,tset,
go" series of words flasheston the screen for thetplayer, then enables all thetcars so that they
cantbegin racing. It then willt"hide" the text object that displaystthe words. This scripttalso
introduces a simple,tbut very useful kind of functiontcalledtcoroutines.

Coroutines are functions thattcan be paused at anytpoint and wait for atspecific event to
occur,tafter which they shouldtcontinue to the next instruction.tFor example, while a functiontwas
running, we could wait fortthe next frame or waittfor 5 seconds. Coroutines maketyour life a lot
easiertwhen dealing with a sequencetoftevents. For example, if youtwanttto display some text for
2tsecondstandtthen want to remove ittagaintyou can do it bytsimply attaching the following
scripttto an object intyour scene;tassuming the object hastatGuiText component:

39
1. We "disable"tall the cars in thetrace, including the AI carstandtthe player’s car. Wetfindtall the
AI cars bytcalling FindObjectsOfType. This returns a listtoftall active loaded objects oftType type.
It willtreturn no assets suchtas meshes,ttextures, prefabs or inactivetobjects. More information
abouttcalling FindObjectsOfType can betfound online. We givetit the type oftthe class we are
lookingtfor, i.e., the AICar,tand get back all instancestof that script. Wetgo through all the
scripttinstances we found and settenabled to false. Sotwhat happens if atscript is enabled
ortdisabled?

The answer is simple:tthe Update function and FixedUpdatetfunction is only called whentthe script
is enabled. By disablingtthe update function we preventtthe car from beingtable to drive.

40
1.The enabledtcheckbox is also visible fortan object or its componentstin the Inspectort(the small
checkbox next totthe title).

2. Then we display thetwords "Get Ready" intour Text object andtthen wait for 3/4tof a second
usingtyield. Then we displaytthe word "Set" andtwait for 3/4tof a second usingtyield.

3. Then we displaytthe word "Go" and enabletall car scripts similar tothow we disabled them.

4. Thetfinal step istto wait for another 3/4 secondtand then remove the Text object,tin a manner of
speaking,tby putting nothing ("") intthe GUIText, and then thetrace can begin.

Buttbefore the cars will actuallytgo, we have to maketsure to have attachedtthe CarStats.jstscript
to all of thetcars (player car and AItcars). Make sure that hastbeen done, and then save thetcurrent
scene so we cantexamine that script.

The CarStatstscript simply tracks that wetdrive through the correct waypoints.tWhen we hit the
starttwaypoint, it will disable thetcar like we did intthe StartGame.js script, sincetthe car has
completed thetrace and it no longertshould drive around the track. Iftit is the player’s car that
hastcompleted the race, then we’lltneed to tell the GameController abouttit. This
"GameController" will betintroduced in 2. GameController andthandle a number of taskstin our
racing gametsuch as showing the highscore etc

1. On Start wetset the activeWaypoint to thetwaypoint after the start so thattwe don’t complete the
game immediately.tWe discussed this also intthe previous chapter of thetproject.

2. In OnTriggerEnter we register whentwe hit a new waypoint. Whentwe hit a waypoint wetfirst
check if it istthe next waypoint so thattthe player can’t skip onetwaypoint or go backwards,
andtthen make the active waypoint thetnext waypoint. When we hittthe startWaypoint we have
completed thetgame and call the ReachedGoaltfunction.

3. The ReachedGoal function uses somethingtcalled GetComponent. This returns the component
oftType type if the game objectthas one attached, null if ittdoesn’t. More information about
accessing othertcomponents can be foundtin the Script Reference andtthe Get Component
information online.

Remembertthattthe CarStats script was attachedtto the PlayerCar and AICar?tWe will need to
handle thesettwo cases differently because theretare two different results if:ta) we have a

41
playertfinishing the race, or b)tif we have an AItcar finishing the race. Iftthe AI car crosses overtthe
start line, it should simplytbe disabled so it stopstdriving. If the player crossestthe start line it
should betalso be disabled but we alsotneed to tell the GameControllertabout it so it can display
highscoretetc. So we usetGetComponent(AICar).

This will return nulltif there is no AICartattached to the game object.tIn that case we simplytignore
it. If we do havetan AICar then we disable it.tWe do the same checktfor the PlayerCar and
thentdisable the player car andtsend a message to thetGameController.

3. THE GAMECONTROLLER:

We’ve mentioned this thingtcalled "GameController" a great deal intthe last few pages. Whattwe
want to create is antobject that will exist throughouttthe entire game, in alltof its scenes, andtact as
a central placetthat we can use to,twell, control aspects oftour game.

Create a new scenet(File -> New) in [D]tGame Setup -> 2 GameControllertand save it as
GameStartup .tIn this scene create a GUITexttobject displaying the name of ourtgame; i.e., Racing
Car Project. Now createtanother new scene in thetsame asset directory calledtMainMenu. There
are two scripts intthe [D] Game Setup -> 2tGameController folder; a Button script and the game
controller.tThe button script implements atsimple mouse over effect and simplytforwards mouse
clicks to thetGameController. Reopen the GameControllertscene and create an emptytobject in the
scene and attachtthe GamerController.js script to it.tLet’s take a quick looktat the first part oftthe
script.

42
This first part of thetscript does three simple things: ittmakes sure the GameController scripttand
the object it’s attachedtto are going to be availabletin every scene; it waitstuntil a key is
pressed;tand then it starts our gametby loading the MainMenu scene.

The GameControllertis scripted to be not destroyedtwhen loading a new level. Thistis done using
the functiontcall: DontDestroyOnLoad (this); in the starttfunction of GameController. Why do we
needtthis? Because, normally, when a newtlevel is loaded, all game objectstfrom the previously
loaded level aretdestroyed. DontDestroyOnLoad allows you to prevent this bytcalling the function
on the objects you don’ttwant to be destroyed.

This is very useful intmany programs: for example, to keep playingtmusic while loading atlevel,
or when you needtto maintain some state from onetlevel to another level. Andtsince
GameController is the onlytgame object we keep alive whentloading levels, this makes it the
idealtplace to perform all the menutcomman.

Anyone familiar with web designtand coding might recognize in thist"GameController" object
many aspects of somethingtknown as a server-side includet... and they would betright.

An include is atbit of code on a websitetthat exists on numerous pages, i.e.,tlike a right column
menu.tSince it’s the same on alltof the pages, it makes sensetfrom a website maintenance

43
standpointtto create a single version oftthe right column menu ontits own, and then use atsingle
line of code on alltof the pages to bring itt(Include it) in the page whentthe page loads. That
way,twhen you need to change the righttcolumn menu, you only need totchange it in one filetand
then all of the pagestare updated.

A GameController object that istset to not be destroyed whenta different scene loads can betused
for a myriad of purposestlike this, as the GameController scripttillustrates.

DisplayHighscore (), which loads the highscoretlevel, waits until user pressedta button, then loads
thetmain menu again. This functionalitytis only possible if thetobject is marked
DontDestroyOnLoad.

What’s goingtto happen with the GameController scripttnow is this: When a GUI buttontis pressed
in the MainMenutscene, we find the GameController instancetand send it a message.tThe message
sent can be changed intthe Inspector,thowever, so when we add newtmenu commands that are
associatedtwith new buttons in our scene,twe don’t need to modifytthe Button script. Insteadtwe
change the action string intthe Inspector and add a newtfunction to GameController.

A GameController thattnever gets destroyed when moving from scenetto scene is the ideal way
tothandle all the menu commands in atgame because we implement the menutcommands in it,
rather than individual Buttontscripts for every menu command. As I mentionedtearlier, the button
script cantthen simply be used to createta simple mouse over effect andtforward mouse clicks to
the GameController.t

44
1. CompletedRace is called from thetCarStats script when the player has finishedtthe race and
displays a familiart"race over" message to the player.tThe game then waits a bittand loads the
highscore. The calculated highscoretis the time it took thetplayer to complete the race. Wetcall
EnterHighScore with the scoretand wait for EnterHighScore totcomplete using yield.
EnterHighscore willtcomplete once the user has finishedtentering his name. Then we gotback to
the main menu.

2.tDisplayHighscore is called when Highscore buttontis clicked. The High Score buttontreferred
to in the scripttis actually located in the MainMenutscene (not GameStartup).

3. Quit simply quitstthe application and the Netgamer button loadstthe first track, which in turn
startstour game.

45
Save the scene and reopentthe [D] Game Setup -> 2tGameController -> MainMenu scene now.
Createtthree text objects (we’ll use astbuttons) named "HighScore", "Quit" and "NewtGame" in
the centre of thetscreen. Attach the single Button scripttto these objects. Let’s take atlook at this
simple script:

1. ThistButton script simply changes the colortof the Text GUI objecttwhen it’s rolled over and
playsta sound if there is antaudio source attached to thetbutton.

2. It changes the text colortback to white when the cursortexits the button object.

46
3. And finally, whentthe text object is clicked, ittsend a message to the GameControllertobject so
that a specific functiontis run.

This, by the way, istan example of why we usedta script and object that
containtDontDestroyOnLoad in the GameStartup scene. ThetGameController object will continue
to existtin the MainMenu scene after we’vetloaded this scene from the GameStartuptscene.

The function that is being calledtin the GameController script is thetstring called "action" in the
Inspector.tThe Button script is passing atmessage to the GameController script sotthat the script
knows which function totrun. So in this case, DisplayHighscore loadstthe highscore, then waits for
the usertto press a key, then goes backtto the main menu. Alltof the buttons in the MainMenutscene
work in the same waytand that is why we neededtonly one Button script.

Technically, the MainMenutscene doesn’t do anything on its own.tIt only forwards messages to
the GameController.tBecause the game controller is storedtour games splash/opening scene that
we calledtGamestartup, you will need to opentthe GameStartup scene and hit Playtfrom that scene
totsee how our game will work,trather than opening the MainMenu scene,twhich on its own, does
nottcontain the GameController script.

You will findtthat this technique will make creating yourtgame GUIs much easier. By
separatingtthe splash screen from the gametoptions screen, and putting a game controller-
typetscript with a DontDestroyOnLoad function in it,tin the same scene as the splashtscreen, we
don’t end up with multipletinstances of a game controller forteach time we load (return to)tthe
main menu level oftour game.

4. HIGH SCORES:

We’re almost done with the racingtgame project and only need totcreate a high score display
thattwill record the top 10tplayer’s names and times. Unfortunately,tthis little requirement happens
to betthe hardest part of the project.tIt was left until the endtso that you’d have well-grounded
introductiontinto programming before tackling it.tBut, no racing game wouldtbe complete without
atway for the playertto record his name after thetrace. One of the many rewards playerstget out of
both causal and hardcoretcomputer games is when they finally gettto see their names listed inta
game’s top scores. Create antnew scene in Game Setup ->t3 Highscore and call it

47
HighScore.tCreate a text object in thetscene called HighScoreTable and attach thetscript of the
same name totit. The HighScoreTable.js is a complextscript fully shown on the followingtthree
pages. Take your time andtreview it function by function. Nowtthat you’ve come this far in
thetproject, you’ll be pleasantly surprised atthow much you’ll understand. Once again,
I’lltexamine and explain the key partstof the script after you’ve readtthrough it.

48
While it may seem complextat first glance, this whole scripttis actually only doing a smallthandful
of tasks. These tasks include:tsetting up an array (think "table") andtpopulating it with the current
hightscores; recording a time and allowingtthe player to enter his orther name; automatically
adding or removingtentries after a race and then rebuildingtthe array; saving the scores to the
game’stpreferences; adding the ability to clear thethigh scores; and making sure the scoretis
correctly formatted. The reason thetscript is so long is that sometof these tasks are made up ofta
number of subtasks and functions.tLet’s go through the function intthe script in details.

49
CHAPTER 7

In thistportion, we create a class thattcontains two variables named score andtname. We will add
these twotvariables to the entriestarray. For those readers who havetnever heard the term before,
antarray is simply a list, andtis one of the most basic data structures intcomputer programming.
Arrays hold some numbertof data elements, generally oftthe same data type. Awake istcalled when
the script istfirst loaded. In this script, wetcall two functions: LoadEntries., whichtreads the entries
from prefs;tand SetupHighscoreTableText, which builds a stringtout of the highscore list
andtassigns it to the HighScoreTablettext object we created intthe scene.

2. OK, the EnterHighScoretfunction is a big one buttis made up of understandable


sections.tEnterHighScore is simply a coroutine (seetpage 27), which runs untiltthe user has entered
histor her name in thethigh score table. It’s made uptof several discrete steps. Firsttwe try to insert
anthighscore entry using InsertEntry. Iftthe player raced to a scoretthat did not make ittinto the top
10tbest scores, we exit the coroutinetat this point.

Then we looptwaiting one frame between every iteration.tA program loop is something that
receivestan event, handles the event, andtthen waits for the next event.tAn event loop usually does
nottend until the conditions set up in the looptare met. In our example, we dotthis using a while
looptwith a yield statement at thetend. In the loop we updatetthe user typed string. Iftthe user hits
enter or returnt("\n") we simply update the highscoretname one last time, write outtthe highscore
table to thetprefs, and then exit.

Thetlast part of this section oftscript simply allows us to showta blinking dot if the user
hasn’ttcompleted entering his name yet.tWe do this by adding at"." to the entered user stringtthe
first half of every second.

3.tInsert Entry. InsertEntry enters antentry and returns the index ortposition. If the player’s score
isttoo low we return -1. Wetfind the right place to puttthe player’s score entry bytlooping through
the highscore list.tAs soon as we find somethingtwith a higher score we Inserttthe score and break.
Then wetneed to Remove any highscores thattdropped out because they are nottin the top 10 scores
anymore.tThen we update the guiTexttto reflect the changes.tFinally, we return the indextof the
score. If notscore was added IndexOf willtreturn -1.

50
4. Change Name. ChangeName simplytchanges the entry at index totthe given name and then
updatestthe guiText.

5. The LoadEntries function doestpretty much what it saystit does: it loads thethighscore from the
prefs. Wetuse the PlayerPrefs class totread and write from the preferencestfile. More information
about PlayerPrefstcan be found online.

All written highscore prefstfollow a simple pattern: highscore’s aretkeyed: "HighScore Score 0"
1, 2,t3 etc, and highscore names aretkeyed: "HighScore Name 0" 1, 2,t3 etc. When loadingtthe
entries we simply retrieve the scoretand name for the index thentadd it to the entries array.
Afterwardstwe fill up the rest oftthe highscore with empty entries.

6. ThetSaveEntries function works like in atsimilar fashion to LoadEntries. This simpletfunction


saves out the high scoretentries in the same pattern astwe loaded them by looping overtthe entries
array writing everytscore and name usingtPlayerPrefs.SetString and PlayerPrefs.SetValue.

7. ThetSetupHighscoreTableText is used to buildta string out of thetentries array. We make


thetprogram go through all entries,ttab separate a player’s name and score,tthen add a newline. It
repeatstitself until all of the topt10 names and scoresthave been displayed.

8. WipeoutPrefs is atutility function that youtcan use to clear the highscoretwhen debugging. It’s
sometimes useful totinclude functions in complex scripts tottrack down where problems might
occur, totreset certain variables or events, etc.tWe used a similar sort oftdebugging function in our
Waypoint scriptton page 25, when we discussedtwhat the OnDrawGizmoSelected function did.

9. ThetFormatScore function is used to nicelytformat the score float. We wantttotsplit up the time
float intotminutes, seconds, and deciseconds integertvalues. The integer valuestare then
concatenated (strung)ttogether to form atnicely formatted time string. And that’stit! Now, that
wasn’t too hardtwas it? Really take your time totreview the sections in this script.tMany of the
techniques usedthere are very simple andtquite commonly usedtin many typestoftgames. You’ll
be usingtmany of these basic scriptingtideas in your own game.tOnce you’ve read through them
andtstart to use and alter themtfor your own games, they willtbecome second nature and you’lltbe
able to look at othertscripts andtbetter understand and utilizetthem for your own projects.

51
CONCLUSION:

“Drtdrifty” is a three dimensional gametthat is a story of atplayer who is going totsurvive himself
to complete alltlevels and reach to his goal.tA different ways of levels inta form of series which
couldtbe completed in through proper way.tRealistic graphics, like a real playertis moving on
screen. This is advancetunity platform. The main goal isthow player will be moved fromtone place
to another to shoot attenemies to complete current level. A 3Dtplatform is given wheretall
characters is moving and firingtat x-axis, y-axis andtz-axis, that is out basic goal.tAudio source
attachedtto video player yields choppytsound when game repetitionstare overrunning. It has
beentstable in advanced Unity. Animation manualtkey framing work flow.tDistinct recording and
showingtmodes in the animation window. AdvancetUnity versions fixed this problem. Buildt&
run games are not workingtafter build it for PC, Mac,tand Mobile. Asset import addedtability to
import visibility from FBXtfiles to model importer. Sotthis new platform give ustan opportunity
to resolves all thesetproblems and come at conclusion to givetfinal report and documentation to
supervisor.tGame development in the gamingtworld has been becoming atbig enterprise lately,
with companiestlike Rovio,tRedlinyx, Remedy and Supercell puttingtout big name titles
andtbecoming very successful. To developta game that could even livetup to the likes oftthe games
from these game companies,tone needs to know the toolstused to do so. Duringtthe project
described in thetthesis Unity 3D was usedtto develop the car game.tUnity is also the game
enginetthat several of these game companiestare using to produce theirttop hits. Having a
firmtfoundation in Unity will give anytgame enthusiast the ability to obtainta job with these
finetgame companies. This report has coveredtall the basics of this game enginetand the
programming language used to createtthe game mechanics used in toptgames today. All games
share sometvery common game mechanics. This reportthas looked at just a fewtthat a programmer
will find intevery game produced today fromtcollision detection to path findingtto timers and finite
state machines.tAll of these game mechanics aretvery important to any game.tThe few mechanics
listed here havetbeen covered in detail as theytpertain to the games made duringtthis project. Every
game producedtused at the minimum collision detection.tMost also used timers and the finitetgame
machine. Path finding was usedtin the flying game just atlittle and was covered astit is a major
parttof many games produced today,tespecially first person shooters andtreal time strategy

52
games.tMany of the games were builttto feature a different aspect oftthe mobile device such asttouch
input or usingtthe accelerometer.

REFRENCES:

[1] "Assest-Store-Unity3d” https://www.assetstore.unity3d.com/en/#!/content/40756

[2]t"Unity3d-Tools” https://unity3d.com/unity/.

[3] Research-Paper.thttp://ieeexplore.ieee.org/document/6295169/

[4] "Resources-products” https://unity3d.com/learn/resources/downloadst

[5] Presentation slidestabout Unity3dtgame “Survivaltshooting," Slideshare, 2009.

[6] ComputertScience & Education (ICCSE), 2012 7thtInternational Conference “Research ontkey
technology basetUnity3D game engine”.

[7] https://www.udemy.com/easiest-unity3d-shooting-game/?site_ref=discudemy.com

[8]thttps://forum.unity.com/threads/japanese-shoot-them-up-game-tutorial.346933/
[9] "Wikipedia, Wikipedia, 2017.t [Online].t Available:t
"t
https://en.wikipedia.org/wiki/Unity_(game_engine)
[10]t "Wikipedia, Wikipedia,t 2017.t [Online].t Available:t
"
https://en.wikipedia.org/wiki/unity3d.t

53

You might also like