Vous êtes sur la page 1sur 22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

OurgameSteredennisinEarlyAccessandplayable!
BacktoPixelnest

Tutorial:Creatinga2Dgamewith
Unity

followusontwitter

Summary

Prev.

Next

Chat,madeforbusiness.Videochat,filesharing&IM.$0/unlimitedusers.
adsviaCarbon

Createaplayeranditsenemies

Pixelnest
18nov.2013
Inthepreviouschapter,wehaveaddedabackgroundand
somepropstoourscene.Itistimetoaddsomeusefulgame
elements,liketheplayer!

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

1/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

Creatingtheplayer
Creatingaplayercontrollableentityneedssomeelements:a
sprite,awaytocontrolitandawaytoletitinteractwiththe
world.
Wewillexplorethisprocessstepbystep.
Let'sbeginwiththesprite.

Addasprite
Hereistheimagethatwewilluse:

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

2/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

(Rightclicktosavetheimage)
1. Copytheplayerimagetothe"Textures"folder.
2. Createanew Sprite .Nameit"Player".
3. Selectthespritetodisplayinthe"Sprite"propertyofthe
"SpriteRenderer"component.
Ifyouhaveanytrouble,refertothepreviouspart.Wedid
exactlythesameprocedureforthebackgroundandprops.
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

3/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

1. Placetheplayerinthe"2Foreground"layer.
2. Changeitsscale. (0.2,0.2,1) shouldbefine.

Awordaboutcomponents
Wehavejusttalkedabouta"SpriteRenderer"component.If
youhaven'tremarked,agameobjectiscomposedofafew
components,visiblesinthe"Inspector"pane.
Bydefault,anemptygameobjectlookslike:

Thisobjecthasonlyonecomponent:a"Transform".This
componentisrequiredandcannotbedisabledorremoved
fromanobject.
Youcanaddasmanycomponentsasyouwantonanobject.
Ascriptisaddedasacomponent,forexample.Mostofthe
componentscanbeenabledordisabledduringthelifetimeof
theobject.

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

4/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

(Youcanclickonthecheckboxtodisabledit.Youcanright
clickonacomponenttoresetit,removeit,etc.)
Note :Componentscaninteractwithothercomponents.Ifanobjecthasa
componentthatrequiresanothercomponentofanobjecttoworkwith,you
canjustdragthewholeobjectinsidethiscomponentanditwillfindthe
correctoneintheobject.

A"SpriteRenderer"isacomponentthatisabletodisplaya
spritetexture.
Nowthatwehavelearnedabouttheconceptofcomponent,
let'saddonetotheplayer!

AddaBoxCollider
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

5/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

Clickonthe"AddComponent"buttonoftheplayerobject.
Choosea"BoxCollider2D".
Thiswillrepresenttheplayerhitbox.
Youcanseethecolliderintheeditor"Scene"viewandtweak
itssizeinthe"Inspector"withthe"Size"property.
Tip :Thereisanotherwaytoeditaboxcollider.Selectagameobjectwitha
boxcolliderandmaintainthe shift keyofyourkeyboard.Youcanobserve
thattheboxcollider(thegreenrectangle)isnowshowingfoursmallhandles
onto.Dragoneofthemtochangetheshapeofthebox.Becareful,theblue
rectanglerepresentsthe Transform componentofyourgameobject,notthe
collider.

Wewillsetthesizeofthecolliderto (10,10) .
It'swaytoolargeforarealshmupbutit'sstillsmallerthan
thesprite:

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

6/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

Forthetimebeing,itwillbeenough.
Tip :Ifyouplantomakeashmup,spendalotoftimetweakingyour
hitboxes.Ingeneral,itshouldfitperfectlyasmallelementinsidetheplayer
sprite.Whatabouttheshipwindowhere?Youcouldalsochangethecollider
shapewitha"CircleCollider2D"forexample.Itchangesnothingtothe
behaviorthankstoUnity,butitwillslightlyimprovethegameplay.

Savetheplayergameobjecttoaprefab.Younowhaveabasic
playerentity!

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

7/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

PolygonCollider2D
Ifyouwantasuperpreciseandcustomshapedhitbox,Unity
offersa"PolygonCollider2D"component.It'slessefficient
butallowsyoutosettheshapeexactlylikeyouwant.
Tip :The"PolygonCollider2D"isliketheothercolliders:youcanmodify
theshapewithyourmouseinthe"Scene"view.Byholding cmd or ctrl ,you
canremoveapoint,andwith shift youcanadjustapointoraddoneonto
thecollidershape.

TheRigidbodymagic
Thereisonelastcomponenttoaddonourplayer:a
"Rigidbody2D".
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

8/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

Thiswilltelltothephysicsenginehowtohandlethegame
object.Furthermore,itwillalsoallowcollisioneventstobe
raisedinscripts.
1. Selectyour Player gameobjectinthe"Hierarchy".
2. Adda"Rigidbody2D"component.
Now,hitplayandobserve:

Theshipisfalling!
Sayhellotoourbelovedgravity.:)
Asnewscenescomewithadefaultgravityandrigidbodies
addamasstoanobject,theshipisnowattractedtothe
bottom.
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

9/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

ThedefaultgravityofUnityis 9.81 ,i.e.theearthgravity.

Gravitycanbeusedinsomekindofgames,butwedon'twant
tohavetohandleithere.Fortunately,itissimpletodisable
gravityonarigidbody.Justset"GravityScale"to0.That'sit,
theshipisflyingagain.
Youmayalsowanttotickthe"FixedAngles"propertyaswe
don'twantourshiptorotatebecauseofthephysics.
Thecompletesettings:

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

10/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

Movingtheplayer
Timeforsomescripting!Sofar,wedidn'tcodeanything.
That'sthepowerof(love)Unity.
InsideUnity,createanewC#scriptinyour"Scripts"folder.
Callit"PlayerScript".
Remark :YoucandoitinJavaScripttoo.Aswesaidbefore,codesnippets
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

11/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

willbeinC#,butitisquiteeasytotranslatethecodefromalanguageto
another.

Openyourfavoriteeditororusethe"Sync"submenu(Click
on"Assets"inthemenubar,thenon"SyncMonoDevelop
Project")toeditthescript.
"SyncMonoDevelopProject" :Thissubmenuisabitweird.First,thename
doesnotchange,evenifyouhavesetupanothereditor.
Wealsorecommendtousethismenuthefirsttimeyouhavetoscript,
becauseUnitywillcreatethesolutionsandlinktheUnitylibrariesinthem
(forVisualStudio,XamarinStudioorMonoDevelop).
Ifyousimplyopenthescriptinstead,thecompilerofyourIDEwilllikely
catchsomeerrorsbecauseitwon'tknowUnity.
Itdoesn'tmatterbecauseyouwillnevercompiledirectlywithit,butitisnice
tohavetheautocompletionontheUnityobjectsandafirstpassonerrors.

IfyoucomefromXNA,youwon'tbelost.
Youcandefinesomemethods(called"Message"aswearenot
usingC#inheritancesystem)thatUnitywillrecognizeand
executewhenneeded.
DefaultscriptscomewiththeStartandUpdatemethods.
Hereisashortlistofthemostused"Message"functions:
Awake()

iscalledoncewhentheobjectiscreated.Seeitas

replacementofaclassicconstructormethod.
Start() isexecutedafter Awake() .Thedifferenceisthatthe
Start()

methodisnotcalledifthescriptisnotenabled

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

12/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

(rememberthecheckboxonacomponentinthe
"Inspector").
Update() isexecutedforeachframeinthemaingameloop.
FixedUpdate()

iscalledateveryfixedframerateframe.You

shouldusethismethodover Update() whendealingwith


physics("RigidBody"andforces).
Destroy() isinvokedwhentheobjectisdestroyed.It'syour
lastchancetocleanorexecutesomecode.
Youalsohavesomefunctionsforthecollisions:
OnCollisionEnter2D(CollisionInfo2Dinfo)

isinvokedwhen

anothercollideristouchingthisobjectcollider.
OnCollisionExit2D(CollisionInfo2Dinfo) isinvokedwhenanother
colliderisnottouchingthisobjectcollideranymore.
OnTriggerEnter2D(Collider2DotherCollider) isinvokedwhen
anothercollidermarkedasa"Trigger"istouchingthis
objectcollider.
OnTriggerExit2D(Collider2DotherCollider) isinvokedwhen
anothercollidermarkedasa"Trigger"isnottouching
thisobjectcollideranymore.
Fiou...Thisexplanationwasabitboring,butunavoidable.
Sorryforthat.
Noteaboutthe2Dsuffix :Youshouldhaveobservednowthatalmost
anythingwetalkedaboutwassuffixedwith"2D".A"BoxCollider2D",a
"Rigidbody2D",the"OnCollisionEnter2D"or"OnTriggerEnter2D"methods,
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

13/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

etc.ThesenewcomponentsormethodshaveappearedwithUnity4.3.
Byusingthem,youareadoptingthenewphysicsengineintegratedinUnity
4.3for2Dgames(basedonBox2D)insteadoftheonefor3Dgames(PhysX).
Thetwoenginesaresharingsimilarconceptsandobjects,buttheydon't
workexactlythesame.Ifyoustarttoworkwithone(favorBox2Dfor2D
games),sticktoit.Thisiswhyweusealltheobjectsormethodswitha"2D"
suffix.

Wewillgetbackonsomeofthemindetailswhenwewillbe
usingthem.
Forourplayerscript,wewilladdsomesimplecontrols:the
arrowkeyswillmovetheship.
usingUnityEngine;
///<summary>
///Playercontrollerandbehavior
///</summary>
publicclassPlayerScript:MonoBehaviour
{
///<summary>
///1Thespeedoftheship
///</summary>
publicVector2speed=newVector2(50,50);
//2Storethemovement
privateVector2movement;
voidUpdate()
{
//3Retrieveaxisinformation
floatinputX=Input.GetAxis("Horizontal");
floatinputY=Input.GetAxis("Vertical");

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

14/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

//4Movementperdirection
movement=newVector2(
speed.x*inputX,
speed.y*inputY);
}
voidFixedUpdate()
{
//5Movethegameobject
rigidbody2D.velocity=movement;
}
}

(Thenumbersinthecommentsrefertotheexplanations
below)
NoteaboutC#conventions :Lookatthe speed membervisibility:it'spublic.
InC#,amembervariableshouldbeprivateinordertokeeptheinternal
representationoftheclassprivate.
ButexposingitasapublicvariableallowsyoutomodifyitinUnitythrough
the"Inspector"pane,evenduringthegameexecution.Thisisapowerful
featureofUnity,lettingyoutweaksthegameplaywithoutcoding.
Rememberthatwearedoingscriptinghere,notclassicC#programming.
Thisimpliestobreaksomerulesandconventions.

Explanations
1. Wefirstdefineapublicvariablethatwillappearinthe
"Inspector"viewofUnity.Thisisthespeedappliedtothe
ship.
2. Westorethemovementforeachframe.
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

15/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

3. Weusethedefaultaxisthatcanberedefinedin"Edit">
"ProjectSettings">"Input".Thiswillreturnavalue
between [1,1] , 0 beingtheidlestate,1theright,1the
left.
4. Wemultiplythedirectionbythespeed.
5. Wechangetherigidbodyvelocity.Thiswilltellthephysic
enginetomovethegameobject.Wedothatin
FixedUpdate() asitisrecommendedtodoeverythingthatis
physicsrelatedinthere.
Tutorialupdate :Ifyouhavereadthistutorialbefore,youmayremember
thatwewereusing transform.Translate directly.Thiswasworkingbecause
translationswereslow,butitisnotrecommendedsinceitcanmessupthe
physics(forthephysicengine,atranslationislikeateleportation,sothereis
nocollision).
Thankstoyourfeedback,weupdatedthescriptstohelppeoplelearnthe
goodpracticesofgameobjectmovement.

Now,attachthescripttothegameobject.
Tip :Youcanattachascripttoagameobjectbydraggingthescriptfromthe
"Project"viewonthegameobjectinthe"Hierarchy".Youcanalsoclickon
"AddComponent"andfinditmanually.

Hitthe"Play"buttonintopoftheeditor.Theshipismoving
andyourgameisrunning!Congratulations,youhavejust
madetheequivalentofa"Hello,World!"foragame:)

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

16/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

Trytotweakthespeed:clickontheplayer,modifythespeed
valuesinthe"Inspector"andlookattheconsequences.

Becareful :Modificationswhenthegameisexecuted(orplayed)arelost
whenyoustopit!It'sagreattoolfortweakingthegameplay,butremember
whatyouaredoingifyouwanttokeepthechanges.
However,thiseffectisalsohandy:youcandestroyyourgamecompletely
duringtheexecutiontotestsomethingnew,withoutbeingafraidofbreaking
yourrealproject.

Thiswasthefirstsignoflifeinourgame!Let'saddmore!

Thefirstenemy
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

17/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

Ashmupisnothingwithouttonsofenemiestoblowup.
Let'suseaninnocentoctopus,named"Poulpi":

(Rightclicktosavetheimage)

Sprite
Timetocreateanewsprite!Again:
1. Copytheimagetothe"Textures"folder.
2. Createanew Sprite usingthisimage.
3. Changethe"Scale"propertyofthe Transform to (0.4,0.4,
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

18/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

1)

4. Adda"BoxCollider2D"withasizeof (4,4) .
5. Adda"Rigidbody2D"witha"GravityScale"of 0 and
"FixedAngles"ticked.
Savetheprefab...andthat'sit!

Script
Wewillscriptasimplebehavior:thePoulpiwilljustmovein
adirection.
Createanewscript"MoveScript".
Wecouldcallit"EnemyScript"butweplantoreuseitlaterin
anothercontext.
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

19/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

Note :ThemodularityprovidedbyUnity'scomponentbasedsystemoffersa
greatwaytoseparatescriptswithdifferentfeatures.Ofcourse,youcanstill
haveonegiantscriptdoingeverythingwithalotofparameters.It'syour
choice,butwehighlyrecommendagainstdoingthat.

Wewillcopysomepartsofwhatwehavealreadywrittenin
the"PlayerScript"formovement.Wewilladdanother
designer(apublicmemberyoucanalterinthe"Inspector")
variableforthedirection:
usingUnityEngine;
///<summary>
///Simplymovesthecurrentgameobject
///</summary>
publicclassMoveScript:MonoBehaviour
{
//1Designervariables
///<summary>
///Objectspeed
///</summary>
publicVector2speed=newVector2(10,10);
///<summary>
///Movingdirection
///</summary>
publicVector2direction=newVector2(1,0);
privateVector2movement;
voidUpdate()
{
//2Movement
movement=newVector2(
http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

20/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

speed.x*direction.x,
speed.y*direction.y);
}
voidFixedUpdate()
{
//Applymovementtotherigidbody
rigidbody2D.velocity=movement;
}
}

AttachthescripttothePoulpi.Hit"Play":itshouldmovejust
likebelow.

Ifyoumovetheplayerinfrontoftheenemy,thetwosprites
willcollide.Theywilljustblockeachotheraswedidn'tdefine
thecollisionbehavioryet.

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

21/22

10/6/2015

CreateaplayeranditsenemiesPixelnestStudio

Nextstep
Youhavelearnedhowtoaddaplayerentity,controlledby
thekeyboard.Then,wecreatedabasicenemywitha
rudimentaryAI.
Now,wewanttodestroythatmovingthing!Andforthat,we
needammo!

Summary

Prev.

Next

clicktogetmoreinformationaboutourupcominggame!

2013pixelnest.iowecraftgamesandapps

http://pixelnest.io/tutorials/2dgameunity/playerandenemies/

22/22

Vous aimerez peut-être aussi