create a player and its enemies

22
Our game — Steredenn — is in Early Access and playable! Back to Pixelnest Tutorial: Creating a 2D game with Unity follow us on twitter Prev. Summary Next Chat, made for business. Video chat, file sharing & IM. $0/unlimited users. ads via Carbon Create a player and its enemies Pixelnest 18 nov. 2013 In the previous chapter, we have added a background and some props to our scene. It is time to add some useful game elements, like the player!

Upload: raulgo23

Post on 17-Aug-2015

23 views

Category:

Documents


3 download

DESCRIPTION

Creacion y edicion 3D UNITY

TRANSCRIPT

10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 1/22OurgameSteredennisinEarlyAccessandplayable!BacktoPixelnest Tutorial:Creatinga2DgamewithUnityfollowusontwitterPrev. Summary NextChat,madeforbusiness.Videochat,filesharing&IM.$0/unlimitedusers.adsviaCarbonCreateaplayeranditsenemiesPixelnest18nov.2013Inthepreviouschapter,wehaveaddedabackgroundandsomepropstoourscene.Itistimetoaddsomeusefulgameelements,liketheplayer!10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 2/22CreatingtheplayerCreatingaplayercontrollableentityneedssomeelements:asprite,awaytocontrolitandawaytoletitinteractwiththeworld.Wewillexplorethisprocessstepbystep.Let'sbeginwiththesprite.AddaspriteHereistheimagethatwewilluse:10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 3/22(Rightclicktosavetheimage)1. Copytheplayerimagetothe"Textures"folder.2. Createanew Sprite .Nameit"Player".3. Selectthespritetodisplayinthe"Sprite"propertyofthe"SpriteRenderer"component.Ifyouhaveanytrouble,refertothepreviouspart.Wedidexactlythesameprocedureforthebackgroundandprops.10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 4/221. Placetheplayerinthe"2Foreground"layer.2. Changeitsscale. (0.2,0.2,1) shouldbefine.AwordaboutcomponentsWehavejusttalkedabouta"SpriteRenderer"component.Ifyouhaven'tremarked,agameobjectiscomposedofafewcomponents,visiblesinthe"Inspector"pane.Bydefault,anemptygameobjectlookslike:Thisobjecthasonlyonecomponent:a"Transform".Thiscomponentisrequiredandcannotbedisabledorremovedfromanobject.Youcanaddasmanycomponentsasyouwantonanobject.Ascriptisaddedasacomponent,forexample.Mostofthecomponentscanbeenabledordisabledduringthelifetimeoftheobject.10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 5/22(Youcanclickonthecheckboxtodisabledit.Youcanrightclickonacomponenttoresetit,removeit,etc.)Note :Componentscaninteractwithothercomponents.Ifanobjecthasacomponentthatrequiresanothercomponentofanobjecttoworkwith,youcanjustdragthewholeobjectinsidethiscomponentanditwillfindthecorrectoneintheobject.A"SpriteRenderer"isacomponentthatisabletodisplayaspritetexture.Nowthatwehavelearnedabouttheconceptofcomponent,let'saddonetotheplayer!AddaBoxCollider10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 6/22Clickonthe"AddComponent"buttonoftheplayerobject.Choosea"BoxCollider2D".Thiswillrepresenttheplayerhitbox.Youcanseethecolliderintheeditor"Scene"viewandtweakitssizeinthe"Inspector"withthe"Size"property.Tip :Thereisanotherwaytoeditaboxcollider.Selectagameobjectwithaboxcolliderandmaintainthe shift keyofyourkeyboard.Youcanobservethattheboxcollider(thegreenrectangle)isnowshowingfoursmallhandlesonto.Dragoneofthemtochangetheshapeofthebox.Becareful,thebluerectanglerepresentsthe Transform componentofyourgameobject,notthecollider.Wewillsetthesizeofthecolliderto (10,10) .It'swaytoolargeforarealshmupbutit'sstillsmallerthanthesprite:10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 7/22Forthetimebeing,itwillbeenough.Tip :Ifyouplantomakeashmup,spendalotoftimetweakingyourhitboxes.Ingeneral,itshouldfitperfectlyasmallelementinsidetheplayersprite.Whatabouttheshipwindowhere?Youcouldalsochangethecollidershapewitha"CircleCollider2D"forexample.ItchangesnothingtothebehaviorthankstoUnity,butitwillslightlyimprovethegameplay.Savetheplayergameobjecttoaprefab.Younowhaveabasicplayerentity!10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 8/22PolygonCollider2DIfyouwantasuperpreciseandcustomshapedhitbox,Unityoffersa"PolygonCollider2D"component.It'slessefficientbutallowsyoutosettheshapeexactlylikeyouwant.Tip :The"PolygonCollider2D"isliketheothercolliders:youcanmodifytheshapewithyourmouseinthe"Scene"view.Byholding cmd or ctrl ,youcanremoveapoint,andwith shift youcanadjustapointoraddoneontothecollidershape.TheRigidbodymagicThereisonelastcomponenttoaddonourplayer:a"Rigidbody2D".10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 9/22Thiswilltelltothephysicsenginehowtohandlethegameobject.Furthermore,itwillalsoallowcollisioneventstoberaisedinscripts.1. Selectyour Player gameobjectinthe"Hierarchy".2. Adda"Rigidbody2D"component.Now,hitplayandobserve:Theshipisfalling!Sayhellotoourbelovedgravity.:)Asnewscenescomewithadefaultgravityandrigidbodiesaddamasstoanobject,theshipisnowattractedtothebottom.10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 10/22ThedefaultgravityofUnityis 9.81 ,i.e.theearthgravity.Gravitycanbeusedinsomekindofgames,butwedon'twanttohavetohandleithere.Fortunately,itissimpletodisablegravityonarigidbody.Justset"GravityScale"to0.That'sit,theshipisflyingagain.Youmayalsowanttotickthe"FixedAngles"propertyaswedon'twantourshiptorotatebecauseofthephysics.Thecompletesettings:10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 11/22MovingtheplayerTimeforsomescripting!Sofar,wedidn'tcodeanything.That'sthepowerof(love)Unity.InsideUnity,createanewC#scriptinyour"Scripts"folder.Callit"PlayerScript".Remark :YoucandoitinJavaScripttoo.Aswesaidbefore,codesnippets10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 12/22willbeinC#,butitisquiteeasytotranslatethecodefromalanguagetoanother.Openyourfavoriteeditororusethe"Sync"submenu(Clickon"Assets"inthemenubar,thenon"SyncMonoDevelopProject")toeditthescript."SyncMonoDevelopProject" :Thissubmenuisabitweird.First,thenamedoesnotchange,evenifyouhavesetupanothereditor.Wealsorecommendtousethismenuthefirsttimeyouhavetoscript,becauseUnitywillcreatethesolutionsandlinktheUnitylibrariesinthem(forVisualStudio,XamarinStudioorMonoDevelop).Ifyousimplyopenthescriptinstead,thecompilerofyourIDEwilllikelycatchsomeerrorsbecauseitwon'tknowUnity.Itdoesn'tmatterbecauseyouwillnevercompiledirectlywithit,butitisnicetohavetheautocompletionontheUnityobjectsandafirstpassonerrors.IfyoucomefromXNA,youwon'tbelost.Youcandefinesomemethods(called"Message"aswearenotusingC#inheritancesystem)thatUnitywillrecognizeandexecutewhenneeded.DefaultscriptscomewiththeStartandUpdatemethods.Hereisashortlistofthemostused"Message"functions:Awake() iscalledoncewhentheobjectiscreated.Seeitasreplacementofaclassicconstructormethod.Start() isexecutedafter Awake() .ThedifferenceisthattheStart() methodisnotcalledifthescriptisnotenabled10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 13/22(rememberthecheckboxonacomponentinthe"Inspector").Update() isexecutedforeachframeinthemaingameloop.FixedUpdate() iscalledateveryfixedframerateframe.Youshouldusethismethodover Update() whendealingwithphysics("RigidBody"andforces).Destroy() isinvokedwhentheobjectisdestroyed.It'syourlastchancetocleanorexecutesomecode.Youalsohavesomefunctionsforthecollisions:OnCollisionEnter2D(CollisionInfo2Dinfo) isinvokedwhenanothercollideristouchingthisobjectcollider.OnCollisionExit2D(CollisionInfo2Dinfo) isinvokedwhenanothercolliderisnottouchingthisobjectcollideranymore.OnTriggerEnter2D(Collider2DotherCollider) isinvokedwhenanothercollidermarkedasa"Trigger"istouchingthisobjectcollider.OnTriggerExit2D(Collider2DotherCollider) isinvokedwhenanothercollidermarkedasa"Trigger"isnottouchingthisobjectcollideranymore.Fiou...Thisexplanationwasabitboring,butunavoidable.Sorryforthat.Noteaboutthe2Dsuffix :Youshouldhaveobservednowthatalmostanythingwetalkedaboutwassuffixedwith"2D".A"BoxCollider2D",a"Rigidbody2D",the"OnCollisionEnter2D"or"OnTriggerEnter2D"methods,10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 14/22etc.ThesenewcomponentsormethodshaveappearedwithUnity4.3.Byusingthem,youareadoptingthenewphysicsengineintegratedinUnity4.3for2Dgames(basedonBox2D)insteadoftheonefor3Dgames(PhysX).Thetwoenginesaresharingsimilarconceptsandobjects,buttheydon'tworkexactlythesame.Ifyoustarttoworkwithone(favorBox2Dfor2Dgames),sticktoit.Thisiswhyweusealltheobjectsormethodswitha"2D"suffix.Wewillgetbackonsomeofthemindetailswhenwewillbeusingthem.Forourplayerscript,wewilladdsomesimplecontrols:thearrowkeyswillmovetheship.usingUnityEngine;//////Playercontrollerandbehavior///publicclassPlayerScript:MonoBehaviour{//////1Thespeedoftheship///publicVector2speed=newVector2(50,50);//2StorethemovementprivateVector2movement;voidUpdate(){//3RetrieveaxisinformationfloatinputX=Input.GetAxis("Horizontal");floatinputY=Input.GetAxis("Vertical");10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 15/22//4Movementperdirectionmovement=newVector2(speed.x*inputX,speed.y*inputY);}voidFixedUpdate(){//5Movethegameobjectrigidbody2D.velocity=movement;}}(Thenumbersinthecommentsrefertotheexplanationsbelow)NoteaboutC#conventions :Lookatthe speed membervisibility:it'spublic.InC#,amembervariableshouldbeprivateinordertokeeptheinternalrepresentationoftheclassprivate.ButexposingitasapublicvariableallowsyoutomodifyitinUnitythroughthe"Inspector"pane,evenduringthegameexecution.ThisisapowerfulfeatureofUnity,lettingyoutweaksthegameplaywithoutcoding.Rememberthatwearedoingscriptinghere,notclassicC#programming.Thisimpliestobreaksomerulesandconventions.Explanations1. Wefirstdefineapublicvariablethatwillappearinthe"Inspector"viewofUnity.Thisisthespeedappliedtotheship.2. Westorethemovementforeachframe.10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 16/223. Weusethedefaultaxisthatcanberedefinedin"Edit">"ProjectSettings">"Input".Thiswillreturnavaluebetween [1,1] , 0 beingtheidlestate,1theright,1theleft.4. Wemultiplythedirectionbythespeed.5. Wechangetherigidbodyvelocity.Thiswilltellthephysicenginetomovethegameobject.WedothatinFixedUpdate() asitisrecommendedtodoeverythingthatisphysicsrelatedinthere.Tutorialupdate :Ifyouhavereadthistutorialbefore,youmayrememberthatwewereusing transform.Translate directly.Thiswasworkingbecausetranslationswereslow,butitisnotrecommendedsinceitcanmessupthephysics(forthephysicengine,atranslationislikeateleportation,sothereisnocollision).Thankstoyourfeedback,weupdatedthescriptstohelppeoplelearnthegoodpracticesofgameobjectmovement.Now,attachthescripttothegameobject.Tip :Youcanattachascripttoagameobjectbydraggingthescriptfromthe"Project"viewonthegameobjectinthe"Hierarchy".Youcanalsoclickon"AddComponent"andfinditmanually.Hitthe"Play"buttonintopoftheeditor.Theshipismovingandyourgameisrunning!Congratulations,youhavejustmadetheequivalentofa"Hello,World!"foragame:)10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 17/22Trytotweakthespeed:clickontheplayer,modifythespeedvaluesinthe"Inspector"andlookattheconsequences.Becareful :Modificationswhenthegameisexecuted(orplayed)arelostwhenyoustopit!It'sagreattoolfortweakingthegameplay,butrememberwhatyouaredoingifyouwanttokeepthechanges.However,thiseffectisalsohandy:youcandestroyyourgamecompletelyduringtheexecutiontotestsomethingnew,withoutbeingafraidofbreakingyourrealproject.Thiswasthefirstsignoflifeinourgame!Let'saddmore!Thefirstenemy10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 18/22Ashmupisnothingwithouttonsofenemiestoblowup.Let'suseaninnocentoctopus,named"Poulpi":(Rightclicktosavetheimage)SpriteTimetocreateanewsprite!Again:1. Copytheimagetothe"Textures"folder.2. Createanew Sprite usingthisimage.3. Changethe"Scale"propertyofthe Transform to (0.4,0.4,10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 19/221) .4. Adda"BoxCollider2D"withasizeof (4,4) .5. Adda"Rigidbody2D"witha"GravityScale"of 0 and"FixedAngles"ticked.Savetheprefab...andthat'sit!ScriptWewillscriptasimplebehavior:thePoulpiwilljustmoveinadirection.Createanewscript"MoveScript".Wecouldcallit"EnemyScript"butweplantoreuseitlaterinanothercontext.10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 20/22Note :ThemodularityprovidedbyUnity'scomponentbasedsystemoffersagreatwaytoseparatescriptswithdifferentfeatures.Ofcourse,youcanstillhaveonegiantscriptdoingeverythingwithalotofparameters.It'syourchoice,butwehighlyrecommendagainstdoingthat.Wewillcopysomepartsofwhatwehavealreadywritteninthe"PlayerScript"formovement.Wewilladdanotherdesigner(apublicmemberyoucanalterinthe"Inspector")variableforthedirection:usingUnityEngine;//////Simplymovesthecurrentgameobject///publicclassMoveScript:MonoBehaviour{//1Designervariables//////Objectspeed///publicVector2speed=newVector2(10,10);//////Movingdirection///publicVector2direction=newVector2(1,0);privateVector2movement;voidUpdate(){//2Movementmovement=newVector2(10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 21/22speed.x*direction.x,speed.y*direction.y);}voidFixedUpdate(){//Applymovementtotherigidbodyrigidbody2D.velocity=movement;}}AttachthescripttothePoulpi.Hit"Play":itshouldmovejustlikebelow.Ifyoumovetheplayerinfrontoftheenemy,thetwospriteswillcollide.Theywilljustblockeachotheraswedidn'tdefinethecollisionbehavioryet.10/6/2015 CreateaplayeranditsenemiesPixelnestStudiohttp://pixelnest.io/tutorials/2dgameunity/playerandenemies/ 22/22clicktogetmoreinformationaboutourupcominggame!NextstepYouhavelearnedhowtoaddaplayerentity,controlledbythekeyboard.Then,wecreatedabasicenemywitharudimentaryAI.Now,wewanttodestroythatmovingthing!Andforthat,weneedammo!Prev. Summary Next2013pixelnest.iowecraftgamesandapps