Intermediate Unity 3D for iOS.pdf
-
Upload
shahzad2mail -
Category
Documents
-
view
235 -
download
6
Transcript of Intermediate Unity 3D for iOS.pdf
15 JANUA
InteIf you're ne
This is a tu
play for em
Unity is ar
Rap
than
Vis
you
Cro
eve
Eas
beg
We just rel
you covere
This time,
cover the m
Some of th
than the “H
Note: This
Shall we p
ARY 2013
rmediew here, you m
utorial by Joshu
merging platfor
rguably the mo
pid developme
n using lower l
sual scene layo
ur app – often w
oss platform. I
en the web!
sy to learn. Un
ginners and is e
leased an epic
ed!
you will create
major concepts
his tutorial will
Heroic Cube” g
s tutorial was m
lay a game? :]
iate Unmay want to sub
Lea
ua Newnham,
rms.
st popular 3D g
ent. Writing yo
level 3D frame
out. Unity com
without having
f you write you
nity is far easie
easy to get star
three-part Beg
e a simple but
s used in Unity
l be review, bu
game ;]
made with Unit
nity 3Dbscribe to my R
arn how to make a
the founder of
game engine fo
our game with U
eworks.
mes with a powe
g to write code
ur game with U
er to learn than
rted!
ginning Unity 3
fun 3D basketb
and will be re
t you’ll learn a
ty 3, so there m
D for iRSS feed or fo
a full 3D game for
f We Make Play
for iOS – and fo
Unity is far qui
erful 3D scene
!
Unity, you can
straight OpenG
3D for iOS seri
ball game calle
ady to create y
a ton along the
may be some sli
iOS: Pollow me on Tw
iOS with Unity!
y, an independe
or many good r
icker than tryin
editor that you
deploy it to iO
GL or lower le
ies, but if you’r
ed “Nothing bu
your own apps!
way since this
ight difference
Part 1/witter. Thanks
ent studio craf
reasons!
ng to write you
u can use to de
OS, Android, W
evel framework
re itching to le
ut Net.” Along
!
s game is much
es with Unity 4
/3 for visiting!
fting creative d
ur own 3D engi
esign a huge pa
Windows, Mac,
ks. It’s friendly
arn more, we’v
the way, you’l
h more complic
4.
digital
ine, or
art of
, or
y to
ve got
ll
cated
DesigniAs with an
should figu
should hav
Let’s give
For this tut
is:
a 3
own
is in
is a
Like most
every spare
annoyance
Your goal
create a ve
and used in
As your tar
casual gam
and starting
So – you w
sketch of w
ing the Appny app, before y
ure out your tar
ve.
this a shot!
torial, let’s assu
3 year old Acc
ns an iPhone
nterested in sp
an office dwell
smartphone us
e moment whe
e!
will be to crea
ery simple (but
n a noisy and d
rget audience i
me play typicall
g the game —
want a simple m
what it could lo
p you begin codi
rget audience,
ume your targe
countant
orts
er with an aver
sers, Bryan’s iP
en he is alone –
ate something th
fun!) app with
disruptive envir
is males betwe
ly ranges betw
to last 5 minut
mechanic, and
ook like:
ing you should
what your idea
Introducing yo
et audience is a
rage commute
Phone is a regu
– and even som
hat offers Brya
h just a single a
ronment, such
en the ages of
ween 4-8 minute
tes.
a quick sports-
d first determin
a is and why it
our target audience
a male between
time of 20 min
ular form of en
metimes when h
an a chance to
and easy to lear
as commuting
12-35, your th
es so aim for a
-related game.
e what it is you
appeals to the
e: Bryan!
n the ages of 12
n per day on pu
tertainment du
he’s bored at di
escape for a fe
rn mechanic. T
g.
heme for the ga
complete gam
How about sho
u’re making –
m, and what fe
2-35 – let’s cal
ublic transport.
uring commutin
inner, much to
ew minutes dur
This way, it can
ame will be spo
ming session —
ooting a basket
and why! You
eatures the app
ll him Bryan. B
.
ng, and in gene
his wife’s
ring his day. Y
n be easily pick
ort related. Mob
— including load
tball? Here’s a
u
p
Bryan
eral,
ou’ll
ked up
bile
ding
a
Ah – you’r
Mechanic/
Go
To
the
Features:
Vis
Sim
Rea
Inc
get
Game asse
Env
Sco
Av
re getting some
/Interaction:
al: score as ma
throw the ball
harder the bal
sually rich and
mple support m
alistic physics
crease the diffic
s more comfor
ets and their fe
vironment
Hoop
Ring
Court
Skybox
oreboard
atar
Idle anima
ewhere! Time t
any points as p
, the player tap
l will be throw
engaging to at
menu (overlay t
to allow for re
culty by movin
rtable with the
eatures:
ation
to flesh out the
ossible within
ps and holds th
wn. Leaving it d
ttract the playe
he game screen
bounds
ng the avatar ar
game).
e functionality
the time limit
eir finger on th
down too long
er
n with the opti
round the court
and componen
he screen. The
will raise a fou
ion to start the
t more frequen
nts you will nee
longer their fin
ul.
game)
ntly as time pas
ed!
nger is held do
sses and the pla
own
ayer
Okay, now
IntroduIf you alrea
Otherwise,
Simply run
Unity is fre
the Registe
You want t
Don’t worr
Your first t
Note: The
through thi
comprehen
athttp://doc
Throw ani
Move anim
w that you have
ucing Unityady have Unity
, you need to d
n the installer,
ee for non-com
er button you w
to start with a n
ry about select
time opening U
introductory v
is tutorial – the
nsive review, c
cs.unity3d.com
imation
mation
e the basic desi
y 3D y, feel free to s
download Unity
and you’ll be r
mmercial use, b
will see on first
new project, so
ting packages t
Unity (after hav
videos and man
ey will give yo
heck out the of
m/Documentati
gn of the app d
skip this section
y before you ca
ready to start u
but you do need
t use. Once Un
o select File\N
to import just n
ving registered
nuals listed here
u a good overv
fficial docume
on/Manual/Lea
down, it’s time
n.
an proceed! Yo
using Unity.
d to register it i
nity is launches
New Project fro
now.
d), you will pro
e are helpful re
view of Unity a
ntation
arningtheInterf
e to start creatin
ou can downlo
in order to use
s, the AngryBo
m the main me
obably see:
esources to che
and what it’s c
face.html.
ng! :]
ad a free trial a
it for your pro
ots sample proj
enu and save it
eck out after yo
apable of. For
at the Unity we
ojects — hence
ect will appear
t wherever you
ou finish going
a more
ebsite.
e
r.
u want.
g
Before you
your Unity
The UnLet’s do a
section.
Unity’s UI
project.
First, the P
means any
Note that s
graphical e
knows whe
Second, th
items witho
particular a
On to the C
buttons at t
are ready t
hide specif
u get started, ha
y projects! :]
nity Interfaquick review o
I is made up of
Project panel p
y resources that
some of the fol
elements for “G
ere to search fo
e Hierarchy pa
out having to n
asset, hover yo
Camera panel!
the top right. M
o optimize you
fic Gizmos in t
ave a quick loo
ace of the Unity Int
f 5 individual p
provides you w
t your game wi
der names that
Gizmos”, which
or them.
anel is a view
navigate throug
our mouse over
! This gives yo
Maximize on P
ur app, as it wil
the game scene
ok at Unity’s u
terface. If you’
panels, each tig
with an overview
ill use, such as
t will appear in
h are design tim
of all assets th
gh the 3D view
r the item you w
ou the point of v
Play maximizes
ll show you dr
e.
user interface, w
’re already com
ghtly related, bu
w and quick ac
scripts, texture
n this panel are
me icons, you
hat are in the cu
w or perform a
want to focus o
view of the cam
s the window w
raw calls and ot
which will beco
mfortable with
ut giving you a
ccess to all the
es, sounds, and
e used for speci
need to place t
urrent scene. Th
multi-select. A
on in the Scene
mera(s) in the
when you selec
ther useful stat
ome the comm
this, feel free t
a different pers
assets of your
d data files.
ific tasks. For i
them in a “Gizm
his allows you
A quick tip — t
e panel and tap
scene. Note the
ct Play. Stats is
ts.Gizmos allow
mand center for
to skip to the n
spective of the
game. “Assets
instance, when
mo” folder so U
u to quickly sele
to get focus of
p the ‘F’ key.
e three toggle
s handy when y
ws you to show
all of
next
s”
n using
Unity
ect
a
you
w and
The panel
panel whic
feel pretty
The selecte
The hand t
allowing y
selected ite
Note: It’s w
first four le
and R (Sca
A quick no
models via
more effici
The final p
object. Thi
All elemen
called Mon
behave in y
Each one o
vary widel
more. Esse
fashion. It’
determines
Note: If yo
functionali
together as
Below is a
above the Cam
ch allows you t
comfortable h
ed item, includ
tool allows you
you to move, or
em by rotating
worth getting c
etters on the ke
ale). Don’t forg
ote about Scale
a the import op
ient.
panel is the Insp
is is an importa
nts in your gam
noBehaviour,
your scene.
of these Compo
ly, and can rang
entially, a Com
’s worth noting
s where the Ga
ou’re familiar w
ity, you attach
s one unit.
screenshot of
mera panel is w
to visually desi
ere! :] If not, d
ding the camera
u to pan around
r translate, the
or scaling it.
comfortable wi
eyboard and th
get your good f
e: it’s best not t
ptions, which y
spector panel –
ant concept to u
me inherit from
are attached to
onents is visibl
ge from anythi
mponent provid
g that all Game
ameObject live
with iOS devel
specialized cla
the Inspector p
where you’ll sp
ign your level.
don’t fret — Un
a, can be manip
d the scene. Th
item around th
ith the short-cu
ey correspond
friend F to focu
to manually sca
ou’ll get into s
– this gives acc
understand so
GameObject.
o each GameOb
le via the Inspe
ing from a simp
es you with a f
eObjects have a
s in 3D space.
opment think o
asses to the obj
panel when th
pend most of yo
If you’re fami
nity is pretty in
pulated using t
he translation t
he scene. Rotat
uts to these tool
in order to the
us in on the sel
ale things unle
shortly, and lea
cess to all the p
take some time
Different Com
bject. These Co
ector panel wh
ple script that y
flexible way to
a Transform c
of your GameO
ject – each give
e camera is sel
our time design
iliar with 3D m
ntuitive and eas
the manipulatio
tool will show
tion and scale a
ls. It’s pretty e
e four tools: Q (
lected item —
ess you are usin
ave the scaling
publicly access
e explaining w
mponents, whic
omponents det
here you can tw
you write, to a
o build up your
omponent – th
Object as an NS
es it different f
lected.
ning your level
modeling tools,
sy to learn.
on tools at the t
handles on the
allow you to m
asy to rememb
(Hand), W (Tr
you will use F
ng it for a visua
to 1.0. This en
ible properties
what this means
ch derive from
termine how th
weak their prop
camera, physi
r game element
heTransform co
SObject. Rathe
functionality bu
ls. This is theS
then you shou
top of the wind
e selected item
manipulate the
ber them; they’
ranslate), E (Ro
a lot! :]
al effect. Scale
nds up being a
of the selected
s.
a component
he GameObject
perties. Compo
ic properties, an
ts in a modular
omponent
er than inheritin
ut they are bun
Scene
uld
dow:
m,
re the
otate),
e your
lot
d
t will
onents
nd
r
ng
ndled
The components here include: Transform (attached to all GameObjects), Camera, GUILayer, Flare Layer, and
Audio Listener. Don’t worry about what they mean yet – I just wanted to show an example of how you can see
components on an object and configure its settings.
Along with the panels, Unity exposes a host of functionality via the toolbar. The two items you’ll be most interested
in are the Game Object and Component items.
The Game Object menu item provides you with a list of items you can add to the current scene. The submenu items
you’ll be interested in are Create Empty and Create Other -> GUI Texture. Create Empty places a new (empty)
GameObject onto the scene. Create Other -> GUI Texture creates a GameObject with the GUITexture component
attached and the currently selected texture as its texture, or the default Unity logo if a texture is not selected.
At this point, you have a basic understanding of the Unity interface. You’ll get a chance to start playing around with
it in the next section, where you’ll start creating your Unity scene!
Game AIn this sect
and quickly
Looking at
you’ll requ
create the m
Here the us
this tutoria
Your desig
He has del
see a direc
Assets tion, you’ll wal
y cover what M
t the list of feat
uire. Imagine y
main menu scr
ser can quickly
al.
gner has also cr
ivered all of th
tory of texture
lk through the
Materials are an
tures from the
your designer h
reen:
y initiate a gam
reated some tex
hese assets as a
s, fonts, image
process of imp
nd what role th
design section
has created the
me and see their
xtures and 3D
a zip file, which
es, and models
porting an asse
hey play in Uni
n of this tutorial
assets for you,
r progress. Not
models for the
h you can down
like this:
et into Unity, di
ity.
l, you have a p
, including the
te that social n
e main level, w
nload here. Af
iscover how U
pretty good han
images and fon
etworking is n
which will look
fter you unzip t
Unity handles as
ndle on what A
nts necessary t
ot implemente
like this:
the file, you sh
ssets,
Assets
to
d in
hould
Now let’s i
select Fold
Start with t
/NothingBu
splash scre
Unity will
assumes th
will result
You’ll nee
panel and s
import a few o
der. Create the
the GUI graph
utNet/GUI fold
een.
automatically
hat the .png file
in a reduction
d to go through
select GUI opt
of the assets int
structure as sh
ics you’lll be u
der. These are
detect the type
es you’re impo
in image quali
h each image a
ion from the T
to your project
hown below:
using in this tut
the graphics th
e of asset you’r
rting will be us
ity when rende
and set the type
Texture type dro
. On the Projec
torial. Drag all
hat you will be
re importing an
sed as 3D mod
ring them as G
e to GUI. To do
opdown (as sh
ct panel in Unit
l the files in the
using for your
nd set some de
del textures and
GUI Textures, w
o this, select an
own below).
ty, click on the
e /NBNAssets/
r GUI, includin
fault properties
d apply compre
which you don
n item, navigat
e Createbutton
/GUI folder int
ng the icon and
s. In this case,
ession to them.
n’t want! :]
te to the Inspec
n and
to the
d
Unity
. This
ctor
Repeat the
Next, impo
/NothingBu
settings as
Now impo
Unity. The
and http://w
Finally, im
folder in U
Note: The
FBX. Unity
just FBX f
guide.
After addin
on each mo
around, yo
above for each
ort the textures
utNet/Textures
they are.
rt the fonts. Dr
ese fonts come
www.dafont.co
mport the mode
Unity.
models for thi
y provides exte
files – for more
ng the models,
odel and inspec
ou can rotate th
h of your imag
s for your mode
s folder in Unit
rag the .ttf files
from www.da
om/varsity.font
ls. Drag the .fb
s game were cr
ensive support
e information o
you should ch
ct in the Previe
he model to insp
ges.
els. Drag the .p
ty. Since these
s from the /NB
font.com (http
t by Unknown)
bx files from th
reated in the op
t for a wide arr
on the file form
heck the texture
ew pane of the
pect it from all
png files from t
e are textures fo
BNAssets/Fonts
://www.dafont
).
he /NBNAssets
pen source (fre
ay of media fo
mats supported
es are correctly
Inspect panel
l sides.
the /NBNAsse
or your 3D mo
s folder into th
t.com/score-bo
s/Models folde
ee) 3D creation
ormats for audio
by Unity, plea
y associated wi
l. If you click o
ts/Textures fol
dels, you can l
e /NothingButN
ard.font by Bo
er into the /Noth
n tool Blender
o, graphics, an
se refer to Uni
ith your model
on the model an
lder into the
leave the defau
Net/Fonts fold
ou Fonts,
hingButNet/M
and exported a
nd 3D assets be
ty’s importing
ls. To do this, c
nd move the m
ult
der in
Models
as
eyond
click
mouse
If your mo
how this lin
MateriaModels are
pipeline th
which dete
can be proc
Open up th
Material in
If your tex
should be (
Select butt
For the pla
odels are grey, t
nking works an
als and Texe associated wi
hat determine h
ermines how U
cessor intensiv
he Materials fo
n this list and c
ture hasn’t bee
(there’s a “Sele
ton to choose a
ayer, the materi
then it’s most l
nd how you ca
xtures ith Materials. M
how the models
Unity renders th
ve, so the best i
older found und
hange the Shad
en associated w
ect” button in t
a texture, or sim
ial should look
likely that the l
an fix it in the n
Materials are a
s vertices are p
he image based
idea here is to a
der Models. He
der from Diffu
with the materia
the bottom righ
mply drag the t
k something lik
link between th
next section – m
assigned a Shad
ositioned and h
d on lighting, n
assign Shaders
ere you can fin
use to Mobile/D
al, then you’ll
ht here). To ass
exture onto thi
ke the following
he Material and
materials and t
der (Shaders ar
how the model
ormal mapping
s specifically fo
d the materials
Diffuse.
see a blank gra
sociate the corr
is spot.
g:
d Texture is br
textures!
re small prgram
l is rasterized t
g, and pixel da
or mobile to yo
s for each mod
ay spot in the b
rect texture, yo
roken. I’ll expl
ms in the graph
o the 2D scree
ata. Some Shad
our Materials.
el. Select each
box where the i
ou can click the
ain
hics
n)
ders
image
e
For the Ho
Transparen
There’s jus
between 3D
factor from
oopTex Materia
nt/VertexLit Sh
st a few things
D modeling too
m 0.01 to 1 as s
al, you’ll requi
hader.
left to do in th
ols, so to get th
shown below:
ire transparenc
his section befo
he models to a
y to be set. Sel
ore you wrap th
reasonable siz
lect this materi
hings up. There
ze, select each o
ial and choose
e is no standard
of them and up
the
dized scaling
pdate their scale
Finally, oppen up the Playyer model and yyou’ll notice a
few child elem
ments, as beloww:
Some of th
and BPlaye
geometry o
detail once
Setting In this sect
working w
with a scen
Before you
camera fac
Your goal
However, t
This is you
following s
Sel
Dra
Cam
Dra
Now that y
panel. Sele
when it’s s
switcher in
hese child elem
erSkeleton are
of the player, a
e you start wirin
up the Scetion you will v
with the Unity s
ne ready for yo
u start visually
cing side on to
is to arrange th
this is easier sa
ur first chance t
steps:
lect the Main C
ag a scene mod
mera window!
ag a player mo
you have some
ect the player, a
selected. You c
n the upper righ
ments will diffe
the objects, th
and finally the i
ng up your pla
ene isually setup th
scene environm
our game.
designing you
the court and t
he scene so it lo
aid than done!
to start playing
Camera in the H
del into the Hie
odel into the Hi
basic objects a
and drag it arou
can also change
ht of the scene
r depending on
he BPlayer (und
items below th
ayer!
he scene of you
ment, discover s
ur scene, consid
the player, and
ooks somewha
:]
g around with t
Hierarchy folde
erarchy panel,
ierarchy panel,
appearing, exp
und the scene u
e the perspectiv
panel.
n what 3D mod
der BPlayerSke
hat are animatio
ur game. The g
some more Co
der the requirem
d positioned so
at like the follo
the Scene, Cam
er, and set X=6
and set X=0, Y
and the Y-rota
periment movin
using the X, Y
ve of how you
deling tool you
eleton) is the m
on frames, whi
goal here is to g
mponents that
ments from the
that one of the
owing:
mera, and Hiera
6.5, Y=7, Z=14
Y=0, and Z=0.
ation to 90.
ng the player ar
Y, and Z arrows
’re looking at t
u are using. In B
mesh data that d
ich will be desc
get some hands
t Unity offers, a
e design stage.
e hoops on the
archy panels in
4, and the Y-Ro
You should se
round the scen
s that appear ne
the scene using
Blender, the BP
describes the
cribed in furthe
s on experience
and finally end
You’ll have th
court can be se
n Unity. Perform
otation to -180
ee it appear in t
ne using the Sce
ext to the playe
g the perspectiv
Player
er
e
d up
he
een.
m the
0.
the
ene
er
ve
At this poin
right spot y
the center (
While you
the Scene.
Player to c
If it isn’t c
the mouse,
Note that n
Now that y
nt add the rem
yourself using
(X=0, Y=0, Z=
’re playing aro
You can also e
center it.
entered the wa
, or hold down
none of these o
you have your
maining objects
the Scene and
=0).
ound with this,
easily zoom in
ay you want it,
the Alt/Option
operations affec
scene roughly
– the basketba
Hierarchy pan
you might not
n on an object in
use your mous
n key to rotate
ct the actual po
set up, time to
all and the hoop
nels – if you ge
tice that whatev
n the scene vie
se wheel to zoo
around and see
osition of objec
configure the
op. See if you c
et stuck, you ca
ver you click o
ew – for examp
om in or out, d
e things from a
cts, it’s just to h
scoreboard!
can arrange the
an always set th
on in Hierarchy
ple, try double
drag the view in
another angle.
help you get a
em into roughly
heir position ba
y is highlighted
clicking on the
n the window w
better view.
y the
ack to
d in
e
with
Separating the Scoreboard from the Scene
Currently, the scoreboard is a child of the background, but you want it as a separate object. So in the Hierarchy
view, drag it from a child of the scene into the root of the Hierarchy. The following dialog will appear – click
Continue.
Note: GameObjects can have children and those children can have children, and so on and so forth. Children of a
GameObject don’t directly inherit functionality of their parent (unless explicitly scripted), but rather use their
parent’s scene space to position themselves. For instance, if the parent was moved along the x-axis, then all the
children of the parent would also be moved e.g. if you held a basketball (your child) and walked forward, the
basketball would move forward with you.
To make a child independent so that it doesn’t inherit the translation, orientation, and scale of its parent (also known
as the object’s “pose”), then simply drag it out of its parent folder as you did here.
The reason you split out the Scoreboard like this was so you could add some 3D Text objects to it, to show the
earned points and remaining time. This is not mandatory but rather an choice for aesthetics and organisation. Doing
so helps (visually) de-couple it from the rest of the scene and gives you the choice of creating a prefab (which we
will talk about later) that you would use if you were to create multiple levels.
The 3D Text object is — surprise! :] — an object that renders text in a 3D environment.
Add a 3D Text object to the scene by selecting the Menu GameObject -> Create Other -> 3D Text. This will place a
new GameObject called New Text into your scene.
Rename this 3D Text object to Points and drag it into your Scoreboard object. Next, associate thescoreboard font
with the 3D text by performing the following steps:
Drag the Project\NothingButNet\Fonts\Scoreboard font to theHierarchy\Scoreboard\Points\Text
Mesh\Font property
Drag the Project\NothingButNet\Fonts\Scoreboard\Font Material material to
theHierarchy\Scoreboard\Points\Mesh Renderer\Materials\Element 0 property
In the inspector for the 3D Text, set the default text to “0000″ and the alignment to right middle aligned. Then use
the Scene panel to position the font on the right spot on the Scoreboard. Note you may have to rotate the text to get it
to show up right – for me, my settings were X=0, Y=0, Z=2.8, Rotation X=270, Y=180, Z=0.
Now perform the same step for the Time text by duplicating the Points text using Cmd-D and positioning it slightly
below. Name the duplicated object Time and set the default text to 00:00.
In the end you should have something that looks like the following:
Turn the
Have you n
let’s light i
Note: Ther
at a render
to support
effect depe
If at all pos
rendering t
Lights On
noticed that the
it up!
re are some con
ing cost. If you
the rendering o
ending on the S
ssible, “bake”
the textures wi
e scene appear
nsiderations to
u have done an
of dynamic ligh
Shader/Materia
all the lighting
th a static light
s pretty dark?
be made when
ny Shader prog
hting. Each lig
al being used, a
g details into th
ting effect app
That’s because
n adding lightin
gramming in th
ght requires eac
and has a high
he texture of the
lied, so that no
e you haven’t a
ng to a scene. A
e past, then yo
ch rendered obj
computational
e object before
o additional com
added any light
Adding lightin
u understand th
ject to calculat
l cost.
e rendering. Ba
mputation is re
ts to the scene,
ng to a scene co
he additional e
te the final ligh
aking is a way
equired to get t
, so
omes
effort
hting
of
the
same visua
Edit -> Ren
In your sim
directional
A full discu
depending
the move a
Camera P
Now turn y
science, bu
and rotatio
You can us
building. A
Hierarchy
Next, in th
upper right
At this poin
al effect. Also,
nder Settings p
mple scene, you
l light GameOb
ussion about li
on where you
and rotate tools
Position
your focus (pun
ut rather more o
on tools in the S
se the preview
As well, you ca
view.
he you should u
t of the Game p
nt, you should
use the scene’
panel.
u will add a lig
bject to your sc
ighting is out o
direct of the li
s in the Scene p
n fully intende
of an art. Play
Scene panel.
available in th
an make use of
update your Ga
panel. If you d
have a view si
s ambient ligh
ght. Select Gam
cene that will b
of scope for thi
ight by rotating
panel to experi
ed! :]) to the co
the part of the
he Game panel
f the little previ
ame screen dim
do not see this,
imilar to the on
t to control the
meObject -> Cr
brighten everyt
s tutorial, but a
g the Direction
iment moving i
orrect positionin
director, and d
directly below
iew window th
mensions to iPh
go to Unity\Bu
ne below:
e lighting inten
reate Other ->
thing up.
a directional lig
nal Light Game
it in different p
ng of the came
drag the camera
w the Scene pan
hat pops up whe
hone Wide 480
uild Settings, a
nsity; this can b
Directional L
ght influences
eObject. Select
positions.
era. Camera po
a into place us
nel where you’
en the camera
×320, via the d
and switch your
be accessed via
ight to add a n
the whole scen
t the light and
sitioning is not
ing the movem
re doing your
is selected in th
dropdown in th
r platform to iO
a the
new
ne
use
t a
ment
scene
he
he
OS.
Your scene is looking pretty good, isn’t it? Feel like a real director yet? :]
Unity Physics: Colliders and Bodies It’s time to add Components to your Scene’s GameObjects so that they can react to each other!
Your goal is to have your objects react to each other when they collide. Luckily, Unity contains a fully-integrated
physics engine and has packaged it up into a suite of Components that can easily dock onto your GameObjects.
Before you add ‘physics’ capabilities to your objects, you’ll need to first take a look into what ‘Physics’ means in
Unity.
Click on the Components -> Physics menu (top toolbar) and have a quick look through the types of components
readily available to you.
Colliders define the physical dimensions of your object, which can be independent of the visual shape of the object.
In general, the colliders are ordered by complexity, and the more complex the object, the performance cost of using
these objects rises.
Where possible, use Box/Sphere to encapsulate your objects, as these Colliders have the least computational load for
your application. The other common Collider you’ll use frequently is the Mesh Collider. This uses the 3D model’s
mesh to define the boundary of your object. In this case, the visual dimensions will equal the physical dimensions.
In addition to physically colliding with other objects, a Collider can be set up as a trigger that can detect collisions
(so you can make something happen programmatically), but not actually cause any collision responses. This will be
useful so you can detect when the ball goes through the basketball net.
In order for objects to react, each object must have some form of body in addition to a collider. This is done by
either adding a Rigidbody or CharacterController to the GameObject.
The best way to get comfortable with Physics is to play around – let’s make that basketball bounce!
Bounce that Basketball! Select the basketball, and add a Rigidbody onto it by selecting Component > Physics > Rigidbody. Then hit the Play
button in the upper center of Unity to preview the gameplay – you’ll see the basketball fall below the floor.
If your basketball “warps” to the middle of the scene when you click play, select the basketball and unclick the
Animation checkbox in the properties and try again. It should stay in the right spot now.
But it wouldn’t be much of a game if the ball was allowed to fly out of the scene! :] You’ll need to create a set of
boundaries that will constrains the ball to the playing area.
To do this, select the scene.Wall object and select Component > Physics > Mesh Collider. Repeat for the
scene.Ground and scene.Background objects. Then select the scene.court object and select Component > Physics >
Box Collider.
If you play the scene again, you’ll see that it still falls through the floor. This is because you still haven’t set up a
collider for the basketball!
So select the basketball and go to Component > Physics > Sphere Collider to set up a sphere collider for your
basketball. It will default to the right size, but you can change the radius if you want in the Inspector’s Sphere
Collider section.
Along with the ball reacting to the environment, you’ll also want it to bounce when it collides with an object. To do
this, you’ll need to assign a special type of Material that Unity provides called a Physic Material.
Where Materials affect how objects look, Physic Materials determine how the object behaves when a collision
occurs. This is associated with the Material property of the GameObjects Collider component.
The following image shows the properties of the Rigidbody attached to the basketball:
On the Project panel, select the Create dropdown menu and then select Physic Material to create aPhysic Material ,
and name it BallPhyMat.
Now set the properties of the Physic Material as shown below. Details on the function of each of the properties
shown below is out of scope for this tutorial, but further information can be found
athttp://docs.unity3d.com/Documentation/ScriptReference/PhysicMaterial.html.
In order to allow the ball to bounce, friction is set fairly low.
To associate the newly created Physic Material to the basketball, select the Physic Material you just created and
drag it to the to the basketball’s Collider material property.
Click the play button again, and this time it falls to the floor and bounces, w00t! :]
As for the hoop, you want it to react to the ball as well as detect when the ball goes through the net. Add aMesh
Collider to the hoop mesh (hoop.LeftHoop).
Also, you want to set up a sensor or “trigger” to detect when the ball goes through the hoop. To do this, add a Box
Collider to hoop.LeftHoop_001, but shorten the box and position it so it’s just below the net (you can do this by
tweaking the values in the Inspector – I changed Center Z to -1.4 and Size Z to 0.2). Also, click the checkbox to set
the trigger property to true.
Note: to vi
the handles
Okay! Tha
MeetingIn this gam
through the
You’ll then
isually resize c
s of the collide
at takes care of
g the Teamme, we want the
e Player is easy
n need to posit
olliders using t
er, allowing you
f the ball — tim
m e player to bou
y enough; go a
ion and size th
the mouse, sele
u to resize it us
me to take a loo
unce the ball an
ahead and add a
he capsule – I c
ect the collider
sing the mouse
ok at the Player
nd for the ball t
a Capsule Coll
changed the hei
r’s object and h
e.
r object! :]
to not roll throu
lider to the pla
ight to 3.8 and
hold down Shif
ugh him. Stopp
ayer GameObje
the Center Y t
ft. This will sh
ping the ball ro
ect.
to 1.8.
how
olling
Note: Colliders are shown in the Scene panel in a green outline — unless they are Mesh Colliders , in which case
it’s the mesh that shows the collision boundaries.
The approach used to bounce the ball requires that the game can detect when the ball collides with the player’s hand.
When this occurs, you will push the ball back down to the ground, just like it happens in real life! To attach the
collider at the correct position, you’ll drill down to the player’s skeleton and add the collider to the hand which will
be used to bounce the ball.
The above screenshot shows you the children of the player GameObject. Where do these children come from? Good
question! :]
These children form the skeleton built to animate the player – the parent is the pelvis which also has theSkeleton
Mesh Renderer component attached to it, which is responsible for rendering the mesh,. The children are
the bones of the skeleton which were built in Blender. ArmIK_L, ArmIK_R, LegIK_L, LegIK_R are just handles
used in Blender and have no function in your app.
Now add a Box
Collider toplayer\BPlayerSkeleton\Pelvis\Hip\Spine\Shoulder_R\UpperArm_R\LowerArm_R\Hand_R and resize
the Collider similar to what is shown below, and set the trigger flag to true.
PrefabsThis sectio
A game ap
have create
template w
the objects
Unity prov
object and
object, it st
To create a
can explici
this object.
Now each
scene. Very
Note: to m
and then se
automagica
Where Congratula
beginner –
Here is a s
click Open
Scenes\Ga
So far, you
pose). You
added a Ph
how Collid
s — and hoon is just an opt
pp normally con
ed a city using
which you can r
s by simply upd
vides the ability
create multipl
till provides an
a Prefab, you c
itly create a Pr
.
time you want
y easy — and
make an update
elect the Game
all propagate to
To Go Froations, you mad
– from here on o
ample project w
n Other, and bro
meScene.
u have explored
u looked at Lig
hysic Material
ders can be use
ow to Taketional note that
nsists of a lot o
the same build
reuse over and
dating the temp
y to do this thro
e identical cop
n efficient way
can either just d
refab via the Pr
t to create anoth
very useful! :]
to your Prefab
e Object -> App
o all associated
om Here? de it! You’ve g
out it will be sm
where we have
owse to the fol
d how GameO
ghting concepts
to the ball to in
ed as triggers o
e Advantat may be usefu
of objects that
ding over and o
over again. As
plate.
ough the use o
pies of it. Howe
of creating an
drag over an ob
roject dropdow
her object from
b, just grab any
ply Changes T
d objects!
gotten through
mooth sailing
e left it off in th
lder. Note that
Objects can cont
s and Colliders
nfluence how i
or by the physic
ge of Themul for you later
are identical bu
over again. An
s well, it gives
f Prefabs. Pref
ever, even if yo
d managing a s
bject from you
wn and then dra
m this template
y Prefab of the
To Prefab optio
the hardest pa
:]
he tutorial so f
the scene won
tain children an
s , and associat
it reacts when
cs engine.
m – feel free to s
ut are used mu
n efficient way
you the advan
fabs allow you
ou don’t want t
setup for each
ur Hierarchy pa
ag the object(s)
e, you just need
e type you’re in
on from the too
art – getting use
far. To open it i
n’t load by defa
nd their childre
ted Physics con
a collision occ
skip if you need
ultiple times. Fo
to do this is to
ntage of being a
u to create one
to create multip
of your game o
anel to your Pr
) from yourHie
d to drag the Pr
nterested in, ma
olbar menu. Th
ed to the Unity
in Unity, go to
ault – to open i
en live in their
ncepts with you
curs, as well as
d a break! :]
or instance, yo
create a maste
able to update
master copy o
ple copies of y
objects.
rojectpanel, or
erarchy panel
refab over to th
ake your updat
he changes will
y GUI as a com
File\Open Pro
it, select
r space (in term
ur objects. You
seeing
u may
er
all of
f an
your
you
into
he
tes,
l
mplete
oject,
ms of
u also
And that’s it for the first part! :] In the next section of this tutorial, you’ll bring your scene to life with interactivity
and animation. That will happen when you’re introduced to Scripting. Until next time!
Beginning Unity 3D for iOS: Part 2/3
Learn how to use Unity to make a simple 3D iOS game!
This is a post by Tutorial Team Member Christine Abernathy, an Engineer on the Developer Advocacy team
at Facebook.
Welcome to the second part of the tutorial series on Beginning Unity 3D for iOS!
In the first part of this series, you learned the basics of Unity by building a very simple project and deploying it to an
iOS device. You’ll want to be sure to go through that part of the tutorial before moving on to this one.
Now in this second part, you’ll add functionality to enrich the project, including better player movement and better
game scenery. You’ll also learn how to use Unity Remote for debugging.
Once again, game on!
Getting Started: A Change of Scenery Open your Unity project from Part 1 of the tutorial. If you don’t have it already, here are the download links:<=""
a="" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-weight: inherit; font-style: inherit; font-size:
13px; font-family: inherit; vertical-align: baseline; color: rgb(0, 104, 55); ">Unity Project, Xcode Project.
You’ll make your changes for this part of the tutorial in a new scene, so you can easily have the old one for
reference later if you’d like.
Select File\Save Scene as… and name your new scene Level_2. The new Level_2 scene should show up in the
Project View.
All the assets you had in the previous scene, such as scripts, are now available for use in your new scene. You can
make changes to the GameObjects present in the Level_2 scene without affecting the same objects in the Level_1
scene.
Gettin’ Jiggy With It First you’ll enhance the player’s movement. Currently your Heroic Cube always moves forward and rotates right.
That’s not very smooth or exciting.
A Charact
movement
For examp
takes in a V
automatica
The charac
that.
To see wha
selectComp
Collider w
Click Repl
You should
script to co
in this scen
Click on th
Componen
ter Controller
. You manipul
ple, you can cal
Vector3 input r
ally account for
cter also slides
at this means, s
ponent\Physic
with a Character
lace.
d see a new co
ontrol the playe
ne.
he gear icon to
nt. The script s
is a Unity com
late the Charac
ll a pre-defined
representing th
r gravity, allow
around any ob
select the Cube
cs\Character C
rController.
mponent in the
er’s movement
the right of the
hould no longe
mponent that yo
ter Controller t
d SimpleMove
he speed with w
wing it to move
bstacles it finds
e GameObject
Controller. You
e Inspector for
t, so you no lon
e MoveSimple
er show up in t
ou can attach to
through script
function to mo
which to perfor
e up slopes and
s in its path wit
(the player) in
u’ll see a dialog
the Character
nger need to att
e script compon
the Inspector.
o a GameObjec
functions.
ove the charact
rm the move. T
d down stairs.
thout your hav
n the Hierarchy
g asking for co
Controller. Yo
tach the Move
nent in the Insp
ct to help create
ter. The Simple
The character’s
ing to write co
y View and
onfirmation to r
ou’re going to c
Simple script t
pector and sele
e more realistic
eMove functio
s movements
ode to take care
replace the Box
create a brand-
to the Heroic C
ect Remove
c
n
e of
x
-new
Cube
Create a ne
new script var speedvar rotat function U var c // Rota tran // Mov var f var c cont} @script
Save your
The last lin
Controller
The Updat
y-axis base
the left/righ
The Input.G
positive va
The Simple
Input.GetA
horizontal
backward a
distance.
Attach the
(Hint: If yo
When you
ew JavaScript a
to open it in thd : float = teSpeed : fl
Update () { controller
ate around y - axnsform.Rotate
ve forward / bacforward : VectcurSpeed : ftroller.Simp
RequireCom
changes.
ne in the script
component.
te() function ge
ed on inputs rep
ht arrows and t
GetAxis() valu
alue a clockwis
eMove functio
Axis(“Vertical”
input, the Inpu
and forward m
new script to y
ou don’t remem
’re done, you s
asset by selecti
he MonoDevel3.0; loat = 3.0;
: CharacterC
xis (0, Input.Ge
ckward tor3 = tranfloat = speepleMove(forward
mponent(Char
specifies that
ets a handle to
presenting left
the A/D keys.
ue ranges from
se rotation arou
on moves the ch
”). This input is
ut.GetAxis() va
movement, resp
your Heroic Cu
mber, it’s Comp
should see the n
ing Assets\Cre
lop Editor. Del
Controller
etAxis ("Horizon
sform.Transfoed * Input.d * curSpeed
acterContro
this script can
the Character C
t/right moveme
-1 to +1. A ne
und the y-axis.
haracter forwa
s triggered by e
alue ranges fro
ectively. You u
ube. By now yo
ponents\Script
new Move Aro
eate\JavaScript
ete the stubbed
= GetCompon
ntal") * rotat
formDirection(VeGetAxis ("Vertd);
oller)
only be attach
Controller com
ents. By defaul
egative value w
rd or backward
either the up/d
m -1 to +1, and
use a speed mu
ou should know
ts\Move Aroun
ound script com
t and name it M
d out functions
nent(Charact
teSpeed, 0);
ector3.forwatical");
ed to a GameO
mponent. It then
lt, the left/right
will result in an
d, depending o
own arrows or
d negative and
ultiplier to cont
w the drill.
nd. :])
mponent in the
MoveAround. D
s and add the fo
terControlle
ard);
Object that has
n rotates the tra
t movement is
n anti-clockwise
n the input obt
r the W/S keys.
d positive value
trol the rotation
player’s Inspe
Double-click th
ollowing code:
er);
a Character
ansform aroun
controlled by b
e rotation and a
tained from
. As with the
es will result in
n angle or the m
ector.
he
d the
both
a
n
move
Why don’t you take your Heroic Cube for a spin using the Unity Editor? Click the Play button and experience your
newfound freedom – oh, the joy of being able to rotate left and right, and move forwards and backwards!
Use the left/right/up/down arrow keys to move around, and also test out the W/A/S/D keys. The player movements
are much smoother now, thanks to the Character Controller component and your scripting genius.
Give yourself a pat on the back before continuing. :]
Debugging with Unity Remote You might have noticed in the last tutorial that testing your project on your iOS device was a bit cumbersome. The
entire process of exporting to an Xcode project and building and running on your device can take quite a bit of time,
which really adds up during development.
The good news is there’s a better way! The fastest way to debug your game on iOS is using an app called Unity
Remote. This allows you to skip the steps of building your project for iOS, launching Xcode and deploying on your
device.
With the Unity Remote iOS app, you can link your iOS device to the Unity Editor and control your Unity Editor
from the iOS device. This allows you to quickly debug your game inside the Unity Editor.
Unity Remote is available for free via the App Store. Download and install the app on your device.
Note: To use Unity Remote, your iOS device and your computer should both be on the same Wi-Fi network. In
addition, the Unity Editor window must be in the foreground in order for this to work. If you send the Unity Editor
window to the background, you’ll get a “Waiting for game view. Press ‘Play’” message on the iOS app.
Click Play in the Unity Editor. On your iOS device, launch the Unity Remote app. Select your computer from the
list that appears. If your computer is not listed, try entering your computer’s IP address in the Unity Remote’s IP
setting.
When Unit
the Unity E
your game
properly te
Test the ga
left/right/u
implement
Double Lucky for y
Select Asse
package.
ty Remote has
Editor. The res
. However, you
est game physic
ame on iOS. Yo
up/down inputs
t some joystick
the Joystiyou, Unity’s S
ets\Import Pac
paired with yo
olution of the d
u’ll want to oc
cs under more
ou’ll find that t
do not exist on
k controls to fix
icks, DoubStandard Assets
ckage\Standar
our computer, y
display on the
ccasionally buil
realistic condi
there’s no way
n iOS (howeve
x this.
le the Funs (Mobile) pack
rd Assets (Mob
your iOS devic
device won’t b
ld the project f
itions.
y to move the p
er, you can still
n kage includes a
bile) to import t
ce should be ab
be ideal, but it’
for iOS and lau
player on your
l control it on y
assets that imp
the relevant ite
ble to control th
’s a great way t
unch it from Xc
device because
your Mac). Ne
plement joystic
ems (as showin
he game runnin
to quickly prot
code so you ca
e your
ext up, you’ll
k functionality
ng below) from
ng in
totype
an
y.
m the
Select the i
Project Vie
imported jo
To resolve
with the w game
Modify the game
Now when
First add th
add a prefa
example, y
In your Pro
Hierarchy
indicated items
ew will contain
oystick script,
this, double-c
arning: eObject.active
e statement to: eObject.SetAc
n you switch ba
he Dual Joystic
ab to a scene by
you could build
oject View, op
View.
s that relate to j
n a new folder
similar to this
lick on the war
e = false;
ctive(false);
ack to the Unity
cks prefab to y
y either draggi
d a prefab that
en the Standar
joystick functi
called Standar
(in yellow at th
rning. That sho
y Editor, the w
your scene. A p
ing it from the
represents a pl
rd Assets (Mob
ionality. Click
rd Assets (Mob
he bottom):
ould open the J
warning should
prefab is a reusa
Project View o
layer and progr
bile)\Prefabs fo
Import. When
bile). You may
Joystick script
vanish. Take t
able and often
or adding it pro
rammatically a
older. Drag the
n the import is c
y see a warning
file. Put your c
that!
customized Ga
ogrammatically
add multiple pl
e Dual Joystick
complete, the
g in Unity 4 wi
cursor on the li
ameObject. Yo
y via a script. F
ayers to a scen
ks prefab into y
th the
ine
ou can
For
ne.
your
You can se
Go back to
ee the joysticks
o the Scene Vie
s by clicking th
ew.
he Game tab too go to the Gamme View:
Click on the triangle next to the Dual Joysticks GameObject in the Hierarchy View. Notice that the Dual Joysticks
GameObject is actually composed of two child GameObjects.
A procedure called parenting was used to set up the joystick parent/child GameObject relationship. Parenting is
useful if you want to create a composite GameObject that has linked GameObjects. For example, you may want the
left and right joysticks to be enabled or disabled at the same time, and it’s much easier to do this via script if they
can be treated as a single object.
Select the LeftJoystick GameObject and note that it has the Joystick script component attached to it. Select
the RightJoystick GameObject and verify the same.
The Joystick script detects touch events on the GUI Texture (the graphic) attached to it and repositions it with
certain constraints. For example, the graphics only move inside a given boundary. The script also normalizes the
position output so that it’s within the -1 to +1 range. This allows you to use the joystick in an iOS environment as a
substitute for Input.GetAxis().
At this point you’ve placed the two joysticks in the scene, but they’re not yet connected to your Heroic Cube to
drive input. You’ll modify the script to assign the right joystick the task of rotating the player, while the left joystick
will move the player back and forth.
Modify the MoveAround script to handle joystick input. Open the script for editing and add two public variables
representing the move and rotate joysticks (at the top where the other variables are): var moveJoystick : Joystick; var rotateJoystick : Joystick;
Then add a new function that looks at the joystick position and returns an output between -1 and +1. Add it right
after the Update() function: function joyStickInput (joystick : Joystick) { var absJoyPos = Vector2 (Mathf.Abs(joystick.position.x), Mathf.Abs(joystick.position.y)); var xDirection = (joystick.position.x > 0) ? 1 : -1; var yDirection = (joystick.position.y > 0) ? 1 : -1; return ( ( absJoyPos.x > absJoyPos.y) ? absJoyPos.x * xDirection : absJoyPos.y * yDirection); }
The joystick input is a Vector2 input, having x and y components. You use the larger, absolute value of x or y to set
the output. You use the direction of the joystick as a multiplier to denote a negative or positive value. This results in
an output value between -1 and +1.
Modify the Update() function to handle input from the Unity Editor or from an iOS device: function Update () { var controller : CharacterController = GetComponent(CharacterController); // Rotate around y - axis var rotatePos = Input.GetAxis ("Horizontal") ? Input.GetAxis ("Horizontal") : joyStickInput(rotateJoystick); transform.Rotate(0, rotatePos * rotateSpeed, 0); // Move forward / backward var forward = transform.TransformDirection(Vector3.forward); var movePos = Input.GetAxis ("Vertical") ? Input.GetAxis ("Vertical") : joyStickInput(moveJoystick); var curSpeed = speed * movePos; controller.SimpleMove(forward * curSpeed);
}
The transfo
input. The
from the le
Save your
has two ne
These varia
the LeftJoy
Joystickva
Click Play
Test the jo
left and rig
moving in
Note: The
the actual d
orm’s Rotate()
Character Con
eft joystick inpu
script changes
ew public varia
ables are not cu
ystickGameOb
ariable. (Or inst
in Unity Edito
ystick function
ght using the rig
the Unity Edit
joystick image
device.
function gets i
ntroller’s Simp
ut.
. Select the pla
ables for Move
urrently assign
bject to the Mo
tead of draggin
or. Start Unity
nality and verif
ght joystick. A
tor.
es might appea
input from eith
leMove functio
ayer GameObje
Joystick and R
ned. With the p
ve Joystick var
ng, you can use
Remote on you
fy that you can
As you move th
ar stretched like
her the left/righ
on gets input fr
ect (the cube) a
Rotate Joystick
player GameOb
riable. Drag th
ed the selector
ur iOS device.
n move forward
he joysticks on
e you see here.
ht arrow (or A/
from either the
and note that th
k.
bject still select
he RightJoystic
next to each v
d and backward
your iOS devi
. Don’t worry,
/D) keys or from
up/down arrow
he Move Aroun
ted, drag
ck GameObject
ariable, as indi
d using the left
ce, you should
they won’t sho
m the rotate jo
w (or W/S) key
nd script comp
t to the Rotate
icated before.)
t joystick and r
d see the joystic
ow up like that
oystick
ys or
ponent
rotate
cks
t on
A ClearNow that y
been occup
Thankfully
sky, add ve
In this sect
the Main C
the cube an
Select Asse
When the i
the newly i
Select the M
r, Bright Syou’ve improve
pying a dull, gr
y, this is fairly
egetation and v
tion, you’ll add
Camera in your
nd is rendered
ets\Import Pac
import is comp
imported asset
Main Camera o
Skybox ed your Heroic
rey world. Tim
simple. Unity
vary the height
d a sky by mea
r game. Once y
to create the sk
ckage\Skyboxe
plete, your Proj
t.
object, then sel
c Cube’s move
me to do some l
includes assets
t of the terrain.
ans of a skybox
you add the com
kybox effect.
es to begin the
ject View shou
lect Componen
ments, how ab
landscaping. :]
s in the Standar
x component. T
mponent, you c
import process
uld have a new
nt\Rendering\S
bout improving
rd Assets pack
The skybox is a
can dress it up
s. Select Sunny
Standard Ass
Skybox.
g the scenery? S
kage that you ca
a big cube obje
by adding a m
y2 Skybox.mat
ets\Skyboxes f
So far the play
an use to create
ect that’s added
material that cov
t, then click Im
folder that cont
er’s
e a
d to
vers
mport.
tains
The new co
the skybox
Click on th
any materi
Click on th
now have t
Your Scen
Game tab t
omponent show
x material you i
he little circula
al assets that a
he Sunny2 Sky
the Sunny2 Sk
ne View will no
to view the sky
ws up in the In
imported earlie
r icon next to t
are available fo
ybox material, t
ybox material
ow magically c
y in the Game V
nspector. Notic
er comes into p
the Custom Sky
or your project’
then close the
assigned to it.
change to displ
View, or click
e that it has a v
play.
ybox variable.
’s use.
Select Materia
ay the sunny sk
the Play button
variable repres
The Select Ma
al dialog. The C
ky you’ve just
n.
enting the mat
aterial dialog s
Custom Skybox
added. You ca
erial. This is w
should pop up l
x material shou
an click on the
where
listing
uld
The sun ha
world.
Don’t FSwitch bac
material (e
You no lon
plane Gam
Select Asse
as come out! A
Forget Youck to the Scene
e.g., grass) and
nger need the p
meObject in the
ets\Import Pac
And even thoug
ur Veggies e View. You ca
objects (e.g., t
plane GameObj
Hierarchy Vie
ckage\Terrain
gh it may appea
an create veget
trees).
ject, as the terr
ew and select D
Assets.
ar overcast, tha
tation by first a
rain will take o
Delete.
at’s encouragem
adding a terrain
over flooring re
ment to add som
n GameObject,
esponsibilities.
me green life to
then adding
Right-click on
o your
n the
Click Impo
You can us
Select Terr
transform p
room to mo
The Terrai
ort to import al
se the imported
rain\Create Te
position to -10
ove.
in (Script) sect
ll the selection
d assets to mod
errain to add a
00,0,-1000 usi
tion contains to
ns. The Terrain
dify the behavi
a terrain GameO
ing the Inspecto
ools that you c
Assets should
ior of a terrain
Object to your
or. This stretch
an use to dress
d show up unde
GameObject.
scene. Select t
hes the terrain o
s up your terrai
er your Standar
the terrain obje
out far enough
in:
rd Assetsfolder
ect and change
h to give your p
r.
its
player
Select the P
You’ll be p
In the Add
Texture2D
Paint tool to br
painting your t
d Terrain Textu
D pop up, then c
ring up the bru
errain with gra
ure dialog, click
click Add:
ushes you can w
ass. Click Edit
k Select in the
work with:
Textures\Add
Texture area, s
Texture:
select the Grasss (Hill) texturee, close the Sellect
Click aroun
If only land
Switch bac
the Terrain
nd in your scen
dscaping could
ck to the Scene
n (Script) secti
ne to paint the
d always be so
e View – now y
ion:
grass. To chec
easy!
you’re going to
ck out your artw
o plant some pa
work, click on
alm trees! Sele
the Game tab:
ect the Place TrTrees tool in
Click Edit
In the Add
Trees\Add Tre
d Tree dialog, c
ee:
click the circulaar icon next to
the Tree entry
y, select the Pallm GameObjecct, then click AAdd:
Set the Bru
Start addin
around as y
trees.
When done
ush Size to 20:
ng trees to your
you place the t
e, your scene s
r scene by click
trees. Try adjus
should look som
king where you
sting the Point
mething like th
u want the tree
light range and
his:
es to be. Hint: Z
d height to see
Zoom into the
more of the sc
scene and pan
cene as you addd
Wow, that
isn’t it?
You can ea
raise and lo
Set the Bru
to vary the
’s much better
asily add some
ower the terrain
ush Size to 20,
e terrain height
! It’s starting to
e height variatio
n height:
then in the Sce
.
o look like a re
on to your terra
ene View, click
eal world down
ain. In the Terr
k on two to thr
n there. But you
rain (Script) se
ree spots aroun
ur terrain’s stil
ection, select th
nd the player (n
ll looking a bit
he leftmost too
not too near, th
t flat,
ol to
hough)
Preview th
to stop the
Save your
Test your p
Settings an
in the Scen
he game and mo
game before m
scene.
project using U
nd in the Build
nes In Build lis
ove around the
making any cha
Unity Remote a
Settings dialo
st. Deselect the
e scene. Tweak
anges you wish
and when satisf
g, click Add C
e Level_1 scene
k the number of
h to keep.
fied, build it as
Current to add t
e to build only
f trees in the sc
s an Xcode pro
the Level_2 sc
Level_2.
cene as you see
oject. Select Fil
cene. The new s
e fit but remem
le\Build
scene will show
mber
w up
Click Build
your iOS d
Not bad, ehWhere to
Well done
be closing
Here are so
padding: 0
vertical-ali
In the final
the bells an
d, choose to re
device.
h? Imagine howo Go From H
! You’ve taken
in on the finish
ome download
px; border: 0px
ign: baseline; c
l part of the tut
nd whistles tha
place the previ
w long it woulHere?
n another big st
h line, too.
ds with all of th
x; outline: 0px
color: rgb(0, 10
torial, you’ll bu
at players expec
ious project if
d have taken to
tride forward in
he code from th
x; font-weight:
04, 55); ">Unit
uild on the proj
ct.
asked and then
o do all this wi
n developing y
he project up un
inherit; font-st
ty Project, Xco
ject by adding
n launch the Xc
ith raw OpenG
your Unity skil
ntil this point:
tyle: inherit; fo
ode Project.
gameplay. Th
code project. D
GL ;]
ls. :] Soon, you
<="" a="" styl
ont-size: 13px;
en you’ll polis
Deploy and test
ur Heroic Cube
le="margin: 0p
font-family: in
h it up by addi
t on
e will
px;
nherit;
ing all
Begi
This is a po
at Faceboo
Welcome t
In the first
mechanism
Then in the
world it oc
In this third
Heroic Cub
To give the
countdown
defeat. :]
You’re alm
GettingFirst, save
tutorial in t
You’ll crea
target desti
the finish l
Select Gam
GameObje
Rename th
the Transfo
inning
ost by Tutorial
ok.
to the third and
part of this ser
m and learned h
e second part o
ccupies with sk
d and final par
be will have to
e player a chall
n timer will add
most to the finis
g Started: Tthe Level_2 sc
this new scene
ate a finish line
ination. The fin
line.
meObject\Crea
ect under which
he object to Fin
orm Position to
g Unity
Lear
l Team Membe
d final part the
ries, you toured
how to deploy
of the series, yo
ky, grass, trees
rt, you’ll add ga
o dash (as cube
lenge, obstacle
d to the drama.
sh line too, so
The End incene as a new s
e.
e using two po
nish line will in
ate Empty to cr
h you’ll add po
nish Line via th
o 0,0,0.
y 3D fo
rn how to use Unit
er Christine Ab
Beginning Un
d the basic Uni
your project on
ou enhanced th
and a variable
ameplay to the
s do) to a finis
es will rain dow
. Success will b
remember – it
n Sight! scene named L
sts and a thick
nclude an invis
reate a new obj
osts, a line, and
he Inspector pa
or iOS
ty to make a simp
ernathy, an En
nity 3D for iOS
ity tools, create
n iOS.
he movement o
terrain.
e project. Instea
h line within a
wn on the Cube
be greeted with
’s hip to be squ
Level_3. You’ll
line connectin
sible wall that’
ject that repres
d a wall.
anel or by righ
: Part
le 3D iOS game!
ngineer on the
tutorial series
ed a game with
of your Heroic
ad of simply m
a certain amoun
e as it zigs and
h cheers – failu
uare!
l be making all
ng them, so tha
s used as a trig
ents the finish
t-clicking the o
3/3
Developer Adv
!
h a simple play
Cube and brou
moving around t
nt of time.
d zags its way t
ure with the de
l your changes
t the player can
gger when the H
line. This is th
object and sele
vocacy team
yer control
ught some life t
the scene, your
o that finish lin
afening silence
for Part 3 of th
n clearly see th
Heroic Cube c
he parent
ectingRename.
to the
r
ne. A
e of
he
he
rosses
Set
To create t
1,3,1. Set t
adjust the y
Hint: View
Drag the P
To create a
the new Ga
of the play
Hint: View
Transform
Next, creat
Other\Cub
the first post, se
the Transform
y position so th
w the scene fro
Post1 GameObj
a second post, s
ameObject from
yer.
w the scene fro
x position to 1
te the wall that
be and rename
elect GameObj
Position to -10
hat the bottom
om the z-axis to
ject and place i
select Post1, ri
m Post1 to Pos
om the y-axis (f
10 should do th
t helps you dete
it to Goal. Set
ject\Create Ot
0,0,20 to put it
of the cylinder
o help you mak
it under the Fin
ight-click and s
st2. Using the M
from above) to
he trick.
ect when the fi
the Transform
ther\Cylinder.
in front of the
r object is just
ke the adjustme
nish Line Gam
select Copy. R
Move Tool, ad
o help you mak
inish line is cro
m Scale to 24,10
Rename it to P
player and to t
a little below t
ents.
meObject to set
Right-click once
djust the x posi
ke adjustments.
ossed. Select G
0,0.5. Set the in
Post1. Set the T
the left. Using
the ground.
t the latter as th
e more and sele
tion so that the
Alternatively,
GameObject\Cr
nitial Transform
Transform Scal
the Move Too
he parent for P
ect Paste. Rena
e post is to the
, setting the
reate
m Position to 0
le to
ol,
Post1.
ame
right
0,2,0.
Move the w
post to the
With the w
the Mesh R
Drag the G
wall to just beh
other.
wall still selecte
Renderer comp
Goal GameObje
hind the two po
ed, open the In
ponent to make
ect and place it
osts. If you nee
nspector\Box C
e the wall invis
t under the Fin
ed to, adjust the
Collider compo
sible.
nish Line Gam
e x scale value
onent and check
meObject to par
e so the wall str
k the Is Trigge
rent the object.
retches from on
er value. Unche
ne
eck
Connect the Dots Next you’ll create the line connecting the posts so that the player can clearly see the finish line. You’ll do this by
drawing a line from one post to the other via script.
Select Asset\Create\JavaScript to create the new script and name it FinishLineRender. Open the script by double-
clicking it in the Project View. Delete the stubbed out functions and add the following code: // The finish line posts var post1 : Transform; var post2 : Transform; var lineColor : Color = Color.green; function Start () { // Set the visual for the finish line posts var lineRenderer : LineRenderer = gameObject.AddComponent(LineRenderer); lineRenderer.SetPosition(0, post1.position); lineRenderer.SetPosition(1, post2.position); lineRenderer.material = new Material (Shader.Find("Particles/Additive")); lineRenderer.SetColors(lineColor, lineColor); }
The LineRenderer class allows you to draw lines in 3D space. Given an array of points, you can use the Line
Renderer component (Components\Effects\Line Renderer) to draw straight lines.
You could have added the Line Renderer component to the Finish Line object and hard-coded the transform
positions for Post1 and Post2, but it’s easier to create the Line Renderer through code. That’s what you’re doing
here.
You draw the line in the Start() function, as it only needs to happen once. First you add the LineRendererscript
interface component, then you set the first and second points for the line to the values from the variable inputs that
will be tied to the two posts. You set the material for the renderer.
Finally, you set the color for the start and end of the line. The line color variable is made public so you can change
it.
Attach the FinishLineRender script component to the Finish Line GameObject.
Hint: You can add the script to the GameObject by selecting the Finish Line object and then tapping the Add
Component button in the Inspector. This should bring up a search box – simply type the first few letters of the word
“FinishLineRender” and it should show you the script.
Assign the
Preview th
finish line.
Next you’l
the Goal G
Open the nfunction O
Post1 and Pos
he game in the U
Stop the game
ll create a new
GameObject. To
new script and OnTriggerEnt
st2 GameObjec
Unity Editor. Y
e.
script that dete
o do this, selec
delete the stubter(other : C
cts to the Post
You should see
ects the finish l
ct Assets\Creat
bbed out functioCollider) {
1 and Post 2 v
e two goal post
line crossing e
te\JavaScript a
ons. Add the fo
variables, respe
ts and a green l
vent, and will
and name the s
ollowing code:
ectively.
line across them
attach this new
criptFinishLin
:
m indicating th
w script to
neDetection.
he
if (other.gameObject.tag == "Player") { Debug.Log("You made it!!!"); } } @script RequireComponent(Collider)
You call the OnTriggerEnter() function whenever another collider enters the GameObject. The GameObject needs
to be set up as a trigger for the event to fire (which you’ve already done for the Goal object).
The player GameObject has a Character Controller component that is a Collider. So when the player runs into
the Goal GameObject, the OnTriggerEnter() event is fired.
In your code, you check if the GameObject that entered the Goal has a tag named “Player”. If that’s the case, the
Heroic Cube has crossed the finish line.
Attach the FinishLineDetection script to the Goal GameObject.
Hint: With the Goal object selected in the Hierarchy View, you can drag the FinishLineDetectionscript from the
Project View to the Inspector\Add Component button to attach the script component to the GameObject.
Before you tag the player, give the player GameObject a name other than plain old “cube”. To keep things
consistent, rename the Cube GameObject to Player.
Now, add a tag to the player object to enable the finish line detection logic. In the Inspector for the player, drop
down the Tag selection and choose Player.
Player is on
game.
Click Play
know that
Yes, the H
levels of co
Create Create an e
launching o
Using the M
the player.
ne of the pre-b
and move the
the player cros
eroic Cube can
omplexity to th
the Launcempty GameOb
obstacles to pu
Move Tool, pla
You can start
built tags availa
Heroic Cube p
ssed the finish
n get to the goa
he game: a time
cher bject and add i
ut a stop to the
ace the launche
with a Transfo
able. Later on,
past the goal lin
line.
al line and win
e-based challen
it to the scene.
Heroic Cube’s
er object in bet
orm Position of
you’ll create y
ne. You should
the game, but
nge and obstac
Name it Laun
s advances.
tween the play
f 0,12,8 and tw
your own tags t
d see a “You m
you can’t let i
cles. First, let’s
ncher. This rep
er and the finis
weak it as neces
to help identify
made it!!!” log m
t off so easy. Y
s add the obstac
resents the evi
sh line in the z
ssary.
y all enemies in
message letting
You’ll add two
cles.
l block empire
direction and
n the
g you
e that’s
above
The main r
Ammunitio
instantiated
and then le
Create Create a cu
hence mor
Give the ob
a material
the constru
reason for the l
on is typically
d in the scene,
et the Launcher
the Obstacube GameObje
e intimidating.
bstacle an inter
from the Chara
uctor_done ma
launcher’s exis
created in Uni
as required, du
r take care of la
cles ect and name it
These are cub
resting look ot
acter Controlle
aterial and the r
stence is to laun
ity by designing
uring gameplay
aunching it ont
Obstacle. Set
bes that have go
ther than the de
er package: sele
relevant textur
nch obstacles,
g GameObject
y. You’ll create
to the hapless p
the Transform
one to the Dark
efault grey mat
ect Assets\Imp
res as shown in
so you need to
ts and then crea
e an Obstacle G
player.
m Scale to 2,2,2
k Side. :]
tter. To match t
port Package\C
n the image bel
o give it some t
ating Prefabs th
GameObject, t
2 so it’s bigger
the completed
Character Con
low, and finally
to launch!
hat can be
turn it into a Pr
than the player
sample, first im
troller, then se
y click Import
refab,
r and
mport
elect
.
The new m
Select the O
Renderer\M
Material di
material should
Obstacle Gam
Materials\Elem
ialog.
show up in yo
eObject. Chang
ment 0 propert
our Project Vie
ge the render m
ty. Click on the
w.
material by mo
e circular icon n
odifying the Ins
next to the pro
spector\Mesh
operty to bring up the Select
Select the cconstructor_doone material yo
ou just importeed. Close the Se
elect Material ddialog.
Now you must tag the Obstacle GameObject so that later on you can take care of clearing out Obstacleinstances of
the scene when a new game is started.
For this, create a new tag named Enemy. Click on Inspector\Tag\Add Tag. The TagManager will show up in the
right side panel. Expand the Tags array by clicking on the triangle next to the Tags label). Set the value of Element 0
to Enemy.
Select the Obstacle GameObject and tag the object with the new Enemy tag.
When Obstacle is instantiated, the code you’ll add will expect a Rigidbody component to be attached to the obstacle.
Set that up by adding a Rigidbody. Select Component\Physics\Rigidbody (with Obstacle still selected):
Click on the Assets folder in the Project View. Create a Prefab of your obstacle by selectingAssets\Create\Prefab.
The Project View should show an empty Prefab. Name it Obstacle.
Note: If you have larger asset icons than in the screenshot above and wonder how you can get the list view of asset
items, simply slide the slider below the asset list all the way to the left. :]
Drag the Obstacle GameObject into this new Prefab.
The Prefab changes to a blue color to indicate that it has been assigned.
Now that you’ve created the Prefab as a reusable asset, you no longer need it in the scene. The launcher will take
care of instantiating an Obstacle instance when needed. In the Hierarchy View, select theObstacle GameObject,
right-click and select Delete.
Release the Krak… Err, Obstacles Next, complete the process by creating logic through a script to launch obstacles.
Create a new script asset and name it ObstacleLauncher.
Hint: You can also right-click in the Project View and select Create\JavaScript to create a script.
Open the new script and replace the stub functions with the following code: var projectile : Rigidbody; var speed = 5; var maxObstacles = 2; var launchInterval : float = 5.0; var target : Transform; private var nextLaunch : float = 0.0; private var numObstaclesLaunched = 0; function Start () {
if (target == null) { // Find the player transform target = GameObject.FindGameObjectWithTag("Player").transform; } } function Update () { if ((numObstaclesLaunched < maxObstacles) && (Time.time > nextLaunch)) { // Set up the next launch time nextLaunch = Time.time + launchInterval; // Set up for launch direction var hit : RaycastHit; var ray : Ray; var hitDistance : float; // Instantiate the projectile var instantiatedProjectile : Rigidbody = Instantiate(projectile, transform.position, transform.rota // Simple block, try to get in front of the player instantiatedProjectile.velocity = target.TransformDirection(Vector3.forward * speed); // Increment the launch count numObstaclesLaunched++; } }
The launcher is programmed to launch a certain number of obstacles just in front of the player. It therefore needs an
input that represents the player. Previously, when assigning GameObjects to script, you’ve done so by dragging the
GameObject to the script variable using the Editor. The Start() function code shows another way to do this.
In Start(), a check is made to see if there is no target assigned. If no target is found, the code looks for a GameObject
with the Player tag and assigns this GameObject to the target variable.
The GameObject.FindGameObjectWithTag() function call is typically an expensive call, as it needs to look through
all GameObjects. So you’ll want to call this in Start() (which gets called once) and avoid putting it in,
say, Update() (which gets called multiple times).
In the code, Update() first checks if the Launcher has sent out the maximum obstacles allowed. If not, it also checks
if a set time interval has passed. This is to avoid launching too many obstacles within a short amount of time.
If it’s time to launch another obstacle, then the Obstacle Prefab is instantiated at the position and rotation
corresponding to the Launcher. The instantiated obstacle is then launched in a direction that matches the player’s
forward direction, so as to land just in front of the player.
Now save your code and tie up loose ends. First, attach the ObstacleLauncher script to the LauncherGameObject.
Assign the Obstacle Prefab to the projectile variable in the script (you can drag the Prefab from the Assets list to the
variable). Assign the Player GameObject to the target variable in the script.
Play the ga
around. Ad
can also ad
Hint: You
along for th
You have m
script that
The FinCreate a ne
following cstatic v
ame in the Unit
djust the launch
djust the finish
can set the Tra
he ride, which
most of the gam
displays the ga
nal Countdew script asset
code: ar gameRunni
ty Editor and v
her’s position s
line by movin
ansform Positi
is one perk of
me functionalit
ame timer, coo
down and name it G
ing : boolea
verify that the b
so that the bloc
ng the Finish L
on to 0,0,2. W
f parenting or g
ty working now
rdinates the ga
GameControlle
an = true;
blocks are laun
cks are launche
Line GameObje
hen you move
grouping related
w. Next you’ll
ameplay and re
r. Open the scr
nched in front o
ed in between t
ect in the z dire
the Finish Lin
d GameObject
pull everythin
esets the scene
ript, delete the
of the Heroic C
the player and
ection, away fr
ne object, the c
ts.
ng together with
to start a new g
stub functions
Cube as it move
the finish line.
rom the player.
child objects co
h a mission con
game.
s and add the
es
. You
.
ome
ntrol
var gameTimeAllowed : float = 20.0; private var gameMessageLabel = ""; private var gameMessageDisplay : Rect; private var timedOut : boolean = false; private var gameTimeRemaining : float = gameTimeAllowed; function Awake() { gameMessageDisplay = Rect(10, 10, Screen.width - 20, 40); } function OnGUI() { GUI.color = Color.yellow; GUI.backgroundColor = Color.black; var text : String = ""; if (timedOut) { gameMessageLabel = "Time's up!!"; } else { text = String.Format( "{0:00}:{1:00}", parseInt( gameTimeRemaining / 60.0 ), parseInt( gameTimeRemaini gameMessageLabel = "Time left: " + text; } GUI.Box(gameMessageDisplay, gameMessageLabel); } function Update() { if (!gameRunning) return; // Keep track of time and display a countdown gameTimeRemaining -= Time.deltaTime; if (gameTimeRemaining <= 0) { timedOut = true; gameRunning = false; } }
Unity provides GUI controls that make it easy to add text labels and button functionality.
ThegameMessageDisplay variable controls where the display is shown. Here you set up the countdown timer to
display across the top of the screen.
OnGUI() is called when an event occurs such as a mouse click, or at least once a frame. GUI.Box() creates a Box
Control using the dimensions you set up initially and with the current game message, which consists of the
countdown time info, a success message or a failure message.
The gameTimeAllowed variable represents the game timer and is set to 20 seconds.
ThegameTimeRemaining variable tracks the currently remaining time. It is initially set to
thegameTimeAllowed value and is decremented by Time.deltaTime in Update().
Time.deltaTime is the time in seconds that the last frame took to complete. Keep in mind that the frame rate may
vary and so this value may also vary. When the gameTimeRemaining value is below zero, thetimedOut flag is set to
true and the player is shown a timeout message.
The code also sets up a gameRunning flag to track if – you guessed it – the game is running. This is useful to stop
the countdown logic and you’ll use it later on to control object behavior when the game is not running.
Attach the script to your Main Camera object:
Play the game and dawdle around until time runs out in order to test the countdown display and the failure case. It’s
a little hard to see, but don’t worry, you’ll change that soon. Stop the game.
Sometimes You Win, Sometimes You Lose You should display a success message when the Heroic Cube crosses the finish line, or rather the invisible wall – it
deserves some encouragement for finishing the challenge! The message will include the time it took to complete the
challenge.
You should also let the player know when time’s up!
The best place to set these messages is the GameController script. However, the finish line detection code is in
another script: FinishLineDetection.
One way you can handle this is to define a function in GameController that the FinishLineDetection script can call
when the player crosses the line. This function can then trigger the desired message display via
theOnGUI() function.
Add two private variables to the GameController script. One will track the time to complete the challenge and the
other will flag a successful mission (the following code can go below the other existing private variables):
private var missionCompleted : boolean = false; private var missionCompleteTime : float = gameTimeAllowed;
Then add the following code to the end of the GameController script: function MissionComplete() { if (!gameRunning) return; missionCompleted = true; gameRunning = false; missionCompleteTime = gameTimeAllowed - gameTimeRemaining; }
MissionComplete() checks if the game is running. If it is, it sets a private missionCompleted flag to true and
the gameRunning flag to false. The time it took to complete the mission is then saved.
Now modify OnGUI() and add the success case (as shown below) to show the time it took to complete the message.
The new code goes just after the var text : String = “”; line and alters the existing if condition: if (missionCompleted) { text = String.Format( "{0:00}:{1:00}", parseInt( missionCompleteTime / 60.0 ), parseInt( missionComple gameMessageLabel = "Mission completed in: " + text; } else if (timedOut) { gameMessageLabel = "Time's up!!"; ...
Switch to the FinishLineDetection script and modify it as follows (the additions are marked with comments): #pragma strict var gameControllerScript : GameController; // 1: new function OnTriggerEnter(other : Collider) { if (other.gameObject.tag == "Player") { Debug.Log("You made it!!!"); gameControllerScript.MissionComplete(); // 2: new } } @script RequireComponent(Collider)
The new code is numbered and does the following:
1. Defines a public variable that points to the GameController script. You’ll assign this shortly.
2. Calls MissionComplete() in the GameController script to trigger the success case.
To assign the gameControllerScript variable, select the Goal GameObject, then select Inspector\Finish Line
Detection and click the circular icon next to the Game Controller Script. In the pop-up dialog, select the Main
Camera GameObject and close the dialog.
Play the ga
displayed w
ame and dash t
when you mak
to the finish lin
ke it in time.
ne, dodging tho
ose nefarious blocks. Check thhat the correct message is
Stop the game and click Play once more. Test the failure case to make sure that that logic still works.
Transformer-ing the Display Font You may have noticed, particularly if you have tested the game using Unity Remote or your iOS device, that the
font displaying the game messages is very small. This is as good an excuse as any to learn about importing fonts into
Unity.
There are a wealth of fonts you can get from sites such as http://dafont.com. The sample you’re going to use was
built with the free Transformers Font. Yes, it’s the original font from the Transformers movie! Maybe your Cube
and blocks are hiding alternate personalities. :]
I added the above font (and a few other resources you’ll need later) to a Resources.zip file that you canhere.
Download the resource archive and extract its contents. Find the font file and drag the Transformers Movie.ttf into
your Project View\Assets folder to import it. Select the Transformers Movie asset in the Project View. The
Inspector shows the import settings. Change the Font Size setting to 36. Click Apply.
You’ve just imported your custom font and it’s ready for use in your project.
Open the GameController script to modify the message font. Define a public variable to set the font: var gameMessageFont : Font;
Change the font used for display labels by modifying OnGUI(), as shown below: function OnGUI() { GUI.skin.font = gameMessageFont; GUI.color = Color.yellow; ...
You assign the gameMessageFont public variable to GUI.skin.font to change the font.
Now select the Main Camera GameObject. Assign gameMessageFont to your newly imported font by dragging the
font asset into the gameMessageFont variable.
Preview the game and verify that the messages are displayed using the new font.
Ah, much better!
It’s Always Play Time! Next, create an in-game button that will control the start of the game and allow the player to restart after a success or
failure. You’ll display the button whenever the game is not running. Recall that you defined agameRunning flag
that you can use to control the button’s visibility.
To create the play button and related functionality, you must modify the GameController script. First define a
private variable that controls the play button text: private var playButtonText = "Play";
Then add a new function called startGame() that sets up a new game: function startGame() { // Reset if starting a new game gameTimeRemaining = gameTimeAllowed; timedOut = false; missionCompleted = false; // Change button text after the initial run playButtonText = "Play Again"; // Kick off the game gameRunning = true; }
Now modify OnGUI() to show the button when the game is not running by adding the following code to the end
of OnGUI() (after all the existing code): // The menu button if (!gameRunning) { var xPos = Screen.width / 2 - 100; var yPos = Screen.height / 2 + 100; if( GUI.Button( new Rect( xPos, yPos, 200, 50 ), playButtonText ) ) { startGame(); } }
Finally, set the gameRunning flag to false. Just modify the existing line for the variable to switch the initial value
from true to false: static var gameRunning : boolean = false;
OnGUI() places a button using the GUI.Button() function. The button text is a variable, so it says “Play” initially
and “Play Again” every subsequent time.
GUI.Button() is wrapped in an if statement. This returns true if the button is clicked. When the user clicks the
button, you kick off the game. startGame() first initializes the game, changes the play button text and finally sets
the gameRunning flag to true.
Preview the game in the Unity Editor. Verify that the play button is initially visible and is hidden after you click on
it. Verify also that when a run is completed, the play button becomes visible once again and that the text has
changed from “Play” to “Play Again”. Note that each time you click on the play button after the first time, the time
is reset and the countdown starts afresh.
But also notice that the player can move even before the play button is tapped. That’s a little annoying, isn’t it?
Don’t let your Heroic Cube get a head start!
To take care of that detail, make use of the gameRunning variable, which is a global variable by virtue of the static
modifier. Add the following code to the top of Update() in the MoveAround script: if (GameController != null && !GameController.gameRunning) return;
You should also disable the launcher from dropping obstacles when the game is not running. Add the following code
at the top of Update() in the ObstacleLauncher script: if (GameController != null && !GameController.gameRunning) return;
Preview the game to ensure that when the game is not running, the player can’t move and obstacles are not
launched.
Every Cube Deserves a Fresh Start While the play button works correctly now, you may notice that even though the timer is reset when a new game is
started, other aspects of the game are not reset.
The obstacles stop falling, as they’ve probably reached the maximum spawn count, but they don’t disappear. Nor
does the Heroic Cube revert back to its original position. A true reset requires that the game start fresh, i.e., the
obstacles are cleared and reloaded and the player position is reset.
The ideal way to accomplish this is to send a message to all interested parties to reset themselves. The Heroic Cube
would then slink back to its original position and the launcher would reload.
One way to do this is to have a reset function defined in a script that handles the reset
behavior.GameObject.SendMessage() can then be used to call this reset function in the hope that a component (a
script) attached to the GameObject handles the function call.
Here’s how you’ll implement this:
1. You’ll define a function called resetGame() in the MoveAround script that resets the player’s position to the
original position when the game started.
2. You’ll define a function called resetGame() in the ObstacleLauncher script to reset the obstacle count to
zero.
3. You’ll loop through a given list of GameObjects that include the player and launcher GameObjects,
calling GameObject.SendMessage(“resetGame”, …) to initiate the reset.
4. You’ll add the reset logic in GameController when the user resets the game.
But code speaks louder than words. First, open the MoveAround script and add the following variables and
functions to it: var originalPosition : Vector3; var originalRotation : Quaternion; function Awake() { originalPosition = transform.position; originalRotation = transform.rotation; } function resetGame() { // Reset to original position transform.position = originalPosition; transform.rotation = originalRotation; }
Then open the ObstacleLauncher script and add this new function: function resetGame() { // Reset to original data numObstaclesLaunched = 0; }
Next open the GameController script and add the following variable: var gameObjectsToReset : GameObject [];
The above line defines an array of GameObjects that will have the resetGame function called on them to initiate a
reset.
Now replace the existing startGame() function with the following (or just update the code to match): function startGame() { // Reset if starting a new game gameTimeRemaining = gameTimeAllowed; timedOut = false; missionCompleted = false; // Change button text after the initial run playButtonText = "Play Again"; // Clean out any enemy objects var enemies = GameObject.FindGameObjectsWithTag("Enemy"); for (var enemy : GameObject in enemies) { Destroy ( enemy); } // Call all game reset methods for (var gameObjectReceiver : GameObject in gameObjectsToReset) { gameObjectReceiver.SendMessage("resetGame", null, SendMessageOptions.DontRequireReceiver); } // Kick off the game gameRunning = true; }
The new code clears out all enemy instances by looking for GameObjects with the Enemy tag. Destroy() is called on
the enemy GameObjects. This clears out the obstacles in the scene.
Then the code processes the gameObjectsToReset array and sends a message to each GameObject to
callresetGame(). It is not mandatory for a component in the array to have implemented resetGame(). You need to
assign the objects to process.
Now select the Main Camera object and note the new public variable for Game Objects To Reset:
Set the Size to 2. The array elements will expand. Assign the Player GameObject to Element 0 and
theLauncher GameObject to Element 1.
Preview the game and verify that the game fully resets itself after a success or failure. Verify that the player position
resets to the original one, that the obstacles are cleared, and that the obstacles start falling once more when the game
is restarted.
This Message Won’t Self-Destruct Your basic gameplay functionality is now complete, but it would be a nice additional touch to show some info about
the game when it’s first launched. All you’re currently showing is a play button. The user doesn’t know what they’re
in for.
Adding some welcome text and a super-short explanation of what the game’s about will make it a lot more user-
friendly. :] The welcome text will use the Transformers font you imported. For the description text, you’ll use the
Arial font that is bundled with Unity.
Create an empty game object, name it Intro and set the Transform Position to 0,0,0.
Select GameObject\Create Other\3D Text to create a 3D Text GameObject and name it Description Text. Set
the Inspector\Text Mesh\Text property to “Get to the finish line before time runs out.” Set the initial Transform
Position to -10,1,12.
Preview th
you can se
Hint: You
Check out
Make any n
Place the D
menu displ
Create a se
text, so set
Set the Fon
property in
he game with th
e it clearly.
’ll likely have
the game with
necessary adju
Description Tex
lay info easily
econd 3D Text
t the initial Tran
nt property to
n the Inspector
he Unity Editor
to play around
h Unity Remote
ustments.
ext object under
via code.
GameObject a
nsform Positio
Transformers
(or by tapping
r and adjust the
d with the x and
e as well and m
r the Intro Gam
and name it We
on to -6,5,10. S
Movie by drag
g the circle with
e position of th
d z positions: x
make sure the te
meObject. You
elcome Text. T
Set the Inspecto
gging that font
h a dot icon ne
he object so tha
x to center to ob
ext is visible w
u’re doing this
This text should
or\Text Mesh\T
asset from the
ext to Font and
at it’s horizonta
bject, and z to
when viewed on
so you can late
d appear above
Textproperty to
e Project View
selecting it fro
ally centered a
zoom in and o
n an iOS devic
er show or hide
e the descriptio
o “Welcome”.
and into the Fo
om the pop-up
and
out.
e.
e the
on
ont
list):
Adjust the
and throug
position of We
gh Unity Remo
elcome Text so
te.
o that you can ssee it clearly wwhen you test thhe game on booth the Unity Edditor
Place the Welcome Text object under the Intro GameObject.
You want to hide the Intro GameObject (and its child objects) when the game is running. Open
theGameController script and make the following changes: var intro : Transform; ... function startGame() { ... // Turn off the intro text for (var child : Transform in intro ) { child.gameObject.renderer.enabled = false; } // Clean out any enemy objects ...
Here you add a new public variable to get a handle to the Intro GameObject. Then you modify startGame()to make
the Intro object invisible by turning off the renderers for its child GameObjects.
Now set the Intro variable by selecting Main Camera and dragging the Intro GameObject from the Hierarchy View
to the Inspector\Game Controller\Intro variable to assign it. Or use the circle dot icon, since it’s easier. :]
Preview the game to test that the text is hidden when the play button is clicked and the game begins.
Every Brave Cube Deserves a Soundtrack Audio plays a big part in the gaming experience, both by providing sensory feedback and creating mood. You’ll add
audio to further enrich the gameplay.
Sound effects will be triggered when the player crosses the line in time, fails their mission, or when an obstacle hits
the ground or bumps into anything. And of course, the game must have some background music! :]
Adding audio with Unity involves attaching an Audio Source component to a GameObject. The Audio Source
component has an Audio Clip property that you can assign to the sound you wish to play. The component has
additional properties that can control when the clip should be played and whether it should loop. The supported
audio file formats include .AIF, .WAV, .MP3, and .OGG.
The following two sites provided the royalty-free music that’s used in this tutorial:
http://incompetech.com/
http://freesound.org/ (registration required to download sounds)
The Resources.zip file you downloaded earlier contains all the audio files that you’ll be using. Feel free to create
your own audio effects instead of using the ones I’ve provided. :]
For your reference (and for the sake of attribution), the original links to the audio files included in the Resources.zip
file are as follows:
victory: 20784__wanna73__crowd-cheering-football-01.wav
defeat: 83916__timbre__benboncan-sad-trombone-tweaked.wav
impact: 30668__hardpcm__hardbassdrum002.wav
background: Gustav Sting.mp3
Do note though that the files in the Resources.zip file have been renamed for the sake of clarity and brevity. Go to
the folder where you originally extracted Resources.zip and import the audio files by dragging them into
your Project View\Assets folder.
When an audio file is imported into Unity, you can specify whether it should be compressed or remain as-is, i.e.,
native. (But note that MP3 and Ogg Vorbis audio are always imported in the compressed format.)
Why does this matter? Compressed files tend to be smaller, but they need to be decompressed as the game runs,
taking up CPU cycles. You generally want to compress background music. For short sound effects, native is better
and tends to provide better sound quality.
If the audio format is compressed, you can choose whether to handle the decompression using hardware, e.g.,
Apple’s hardware codec if running on an iOS device. Hardware is faster, but the hardware can handle one
compressed music file at a time.
You can also mark sounds as 3D. This means that when the sound is played, the effect will be relative to the 3D
position of the GameObject. For example, if the GameObject is far away, the sound will be quieter.
Select the background audio in the Project View to show the Import Settings. Unselect the 3D Sound option. Select
Hardware decoding. Click Apply to save the setting changes.
The other audio files are .WAV files and you do not need to modify the default Import settings, which should be set
to 3D and native audio format.
For sounds to be heard, your scene needs an Audio Listener component to be added to a GameObject. There can
only be one Audio Listener in the scene. The listener will pick up sounds from the audio sources close to it and send
it to the device speaker.
By default, an Audio Listener is attached to the Main Camera. You can leave it there or attach it to a different
GameObject: the player, for example.
In this game, you’ll keep the Audio Listener on the Main Camera, but you can experiment with the different options
when you build your own games.
The Sounds of Victory and Defeat You’re going to attach audio to the Goal GameObject that simulates a crowd cheering or jeering at the finish line.
Select the Goal GameObject in the Hierarchy View and add an audio source by selectingComponent\Audio\Audio
Source. Set the victory audio asset to the Inspector\Audio Source\Audio Clip property. De-select the Play on
Awake option.
Now create a new JavaScript asset that will be used to play either a victory sound or a defeat sound. Name the new
script FanReaction. Open the new script, remove the stub functions and add the following code: var audioVictory : AudioClip; var audioDefeat : AudioClip; var volumeVictory : float = 2.0; var volumeDefeat : float = 2.0; function playSoundOfVictory(isVictory : boolean) { // Stop any current audio if (audio.isPlaying) audio.Stop(); // Play either the sound of victory or defeat. audio.clip = isVictory ? audioVictory : audioDefeat; audio.volume = isVictory ? volumeVictory : volumeDefeat; audio.Play(); } function resetGame() { // Reset to original state, stop any audio if (audio.isPlaying) audio.Stop(); } @script RequireComponent(AudioSource)
The script takes in two audio clips, one for victory and one for defeat. The playSoundOfVictory() function first
stops any audio that’s currently playing, then plays the required audio based on the isVictory input.
The resetGame() function stops any audio that’s playing. You’ll shortly wire up the GameController to
callresetGame() every time the game is restarted.
Attach this new script to the Goal GameObject. Set the victory audio asset to the Audio Victory variable. Set
the defeat audio asset to the Audio Defeat variable.
Edit the GameController script and make the following changes: var fanReactionScript : FanReaction; ... function Update() { if (!gameRunning) return; // Keep track of time and display a countdown gameTimeRemaining -= Time.deltaTime; if (gameTimeRemaining <= 0) { timedOut = true; gameRunning = false; // Play the sound of defeat fanReactionScript.playSoundOfVictory(false); } } ... function MissionComplete() { if (!gameRunning) return; missionCompleted = true; gameRunning = false; // Play the sound of victory fanReactionScript.playSoundOfVictory(true); missionCompleteTime = gameTimeAllowed - gameTimeRemaining; }
The code defines a new public variable that references the FanReaction script. You modifyMissionComplete() to
call playSoundOfVictory(), passing in true to play the victory sound. You also modify Update() to
call playSoundOfVictory(), passing in false to play the defeat sound.
You can now link the FanReaction script in the Goal GameObject with the variable in the Main
Camera‘sGameController script component. Select Main Camera and then click on the circular icon next to the
fanReactionScript variable under the GameController component in the Inspector. In the dialog that pops up, select
the Goal GameObject, then close the pop-up.
To call resetGame() in FanReaction, select the Main Camera Object. In the Game Controllercomponent section in
the Inspector, increase the Game Objects To Reset array size from 2 to 3. Set theGoal GameObject to Element 2.
Preview the game and test out the victory and defeat scenarios to make sure the game plays the correct sounds.
Verify that the sounds are stopped when you hit Play Again.
Thud in 3D It would also be nice to have some sort of a sound when obstacles hit the ground. To achieve this, you’ll attach an
audio source to the Obstacle Prefab, then detect collisions so you can play the impact audio when the obstacles fall
or bump into anything.
Add an Audio Source component to the Obstacle Prefab. Assign the impact audio to the Audio Clipproperty.
Create a new JavaScript asset and rename it to ObjectCollision. Edit the script, delete the stubbed functions and add
the following code: var impact : AudioClip; function OnCollisionEnter () { audio.PlayOneShot(impact); } @script RequireComponent(AudioSource)
The code implements the predefined OnCollisionEnter() event function and calls the audio.PlayOneShot()function
to play the impact audio clip. audio.PlayOneShot() illustrates another way to play audio, allowing you to pass in the
audio you wish to play.
Attach the script to the Obstacle Prefab. Set the impact audio asset to the Impact variable in the script.
Preview the game and verify that you hear a pleasing thud sound when obstacles hit the ground or another object.
Note that closer the obstacles are to the player, the louder the sounds.
A Little Cube Music Your game’s almost complete. But there’s one thing missing – some background tunes.
Music does a lot to set the mood for a game. It can get a user’s adrenaline flowing and help them “feel” the game
environment by providing contextual clues like bird sounds or wolves howling. So add some music!
Add an Audio Source component to the Main Camera GameObject. Set the background audio asset to the Audio
Clip property.
Select the Play on Awake and the Loop options. These ensure that the background music starts as soon as the game
starts and that it will play continuously.
Adjust the volume property to 0.1 so it doesn’t drown out the other sounds. If you’re using your own sounds, tweak
the volume level depending on your music’s default volume level to achieve the same goal. Users should be able to
hear all the sound effects while the background music is playing.
Preview the project in the Unity Editor. When completely satisfied, deploy the project to your iOS device. You’ll
need to add the Level_3 scene in the Build Settings.
Test out thhe gameplay onn your iOs deviice while you eenjoy the soundds you’ve adde
ed.
Your Hero
Where Congratula
much verv
gaming.
Here are th
border: 0px
baseline; c
Believe it o
intermedia
In the mean
games!
oic Cube has a
To Go Froations, you’ve m
ve and vigor as
he source files
x; outline: 0px
olor: rgb(0, 10
or not, you’ve j
ate tutorial serie
ntime, be sure
soundtrack to g
om Here? made it to the
your Heroic L
with all of the
x; font-weight:
04, 55); ">Unity
just scratched
es that will tak
to stop by the
glorify its brav
end of this whi
Little Cube. Thi
code from this
inherit; font-st
y Project, Xco
the surface – th
ke you to the ne
forums with y
very!
irlwind walkth
is could be the
s tutorial series
tyle: inherit; fo
de Project.
here’s a whole
ext level with U
our questions a
hrough of the b
beginning of a
s: <="" a="" sty
ont-size: 13px;
e lot more to le
Unity!
and feedback,
asics of Unity!
a wonderful jou
yle="margin: 0
font-family: in
arn. Stay tuned
and have fun b
! You’ve show
urney with Un
0px; padding: 0
nherit; vertical-
d for an upcom
building aweso
wn as
ity
0px;
-align:
ming
ome