2 d game play tutorial

49
2D Gameplay Tutorial Providing 2D Gameplay with Unity 2 Author: Graveck Interactive Last Revision: 19-FEB-2008

Upload: sdddds

Post on 13-Apr-2015

25 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 2 d Game Play Tutorial

2DGameplayTutorialProviding2DGameplaywithUnity2

Author:GraveckInteractive

LastRevision:19­FEB­2008

Page 2: 2 d Game Play Tutorial

Contents

1. IntroductionWhy2DistheBee'sKnees 4Prerequisites 6

2. SettingTheSceneGettinginthe2DMind­Set 7ACloserLook 9SettingtheLevelAttributes 10ObjectProfile:LevelAttributes 12ObjectProfile:DeathZone 13SettingUpthePlatforms 13ObjectProfile:Platform(Prefabs) 15ObjectProfile:Pre­AssembledPlatform 16IntroducingLerpz,OurLovelyCharacter 17PlacingLerpz 18DirectingtheCamera 19ObjectProfile:Character(Lerpz) 20LightingourScene 22SpicinguptheCharacter 24TheCamera 26ObjectProfile:MainCamera 27ContinuingourLevel 28ScriptProfile:CameraTargetAttributes 28HandlingRigidbodies 29ObjectProfile:Crate 30Exercise 31MovingPlatforms 32ObjectProfile:MovingPlatform 33TheSpaceship 34ObjectProfile:Spaceship 35WellDone! 36

3. DelvingDeeper:ScriptingExamplesStudyingtheScripts 38MovingPlatformParticleEffects 38

Page 3: 2 d Game Play Tutorial

TheCameraScrollingScript 40StreamlineYourWorkflow 41SpaceshipScriptPart1:DefiningHelperClasses 43SpaceshipScriptPart2:ControllingtheSpaceship 44SpaceshipScriptPart3:SpecialEffects 47Finished! 47

4. What'sNext?YourTurn 48

Page 4: 2 d Game Play Tutorial

Introduction

Why2DistheBee'sKneesItisnosecretthatUnitycanhelpyoucreategreatthree­dimensionalgameswithease.Itsrawpowerandflexibilityallowsevenbeginnerstocreateimpressivegameswith­outmuchdifficulty.Unityisundoubtedlyagreat3Dgameengine­­sowhyonearthwouldyouwanttocreatea2Dgamewithit?

Forcertaingametypes,thatextra"D"in3Dcanbeahindrance.Somegamessimplyworkbetterwithtwo­dimensionalgameplaymechanics.Thinkofthosesimpleandfun2Dside­scrollinggamesyouhaveplayedinthepast,ormaybeyouhaveasimplepuz­zlegameideathatwouldworkbestconstrainedtotwodimensions­­thelistkeepsgoingbutthebottomlineismanygamescanbenefitbytheuseofonlytwodimen­sions.

Two­dimensionalgamesarealsocommonlyeasierforthecasualgamertounderstand,whichissomethingtoconsiderifyou'reasmallgamedeveloper(seethearticle"Cas­ualGamesasaBusiness").

Luckily,Unityisextremelyflexibleandcaneasilyhandle2Dgameplay!ItsworldclassAgeiaPhysXishighlyadaptableandcanbeconstrainedinmanywaysincludingtwodimensions.

Inthistutorialwedefinea2DGameasagamewheregraphicsarestillin3D,butre­strictedmotioncausesthephysicsandgameplayonlytooccurinasingle2Dplane.Thisletsususe3Dmodelsforourcontentandmakeslifeeasierforartistsanddevel­opersalike.Onecouldsaythatwe'reusingthebestofbothworlds:theeaseof2D

Sometimes2Dgameplaycallsandyoucan'tresistitsalluringcharm!Unitycanhandleit.

Thistutorialshowsthestepsyouneedtocreateabasic2D­styleplatformgame.

Page 5: 2 d Game Play Tutorial

gameplayandthebeautyof3Dgraphics­­withtheaddedattractionthatexistingde­velopersalreadyhaveagood3Dassetproductionpipelineinplace.

Thistutorialwillguideyouinbuildinga2Dplatformgame.Wehavedesignedthistutorialwithbeginner/intermediate­levelusersinmind;weonlyaskthatyouhaveabaselineknowledgeofUnity.Wehavealsoincludedsomeadvancedconceptsthatmaybeofinteresttomoreseasonedusers.

Webeginbygettingyouintothe2Dmind­set.Thenwewillwalkyouthroughbuild­inga2Dworldinwhichyourcharacterwillmovearound.Afteraddingafewcoolob­staclesandscenery,we'lllastlyaddarocketshipfortheplayertofly.

Wehopeyouenjoythistutorialasmuchaswehadfuncreatingit!

Thetutorial’sdemolevelinaction.

5

Page 6: 2 d Game Play Tutorial

PrerequisitesHerearethetoolsandknowledgeyoushouldhavebeforeyoubeginthistutorial:

• Unity2

Althoughyoucanbenefitfromthistutorialifyou'reaUnity1.xuser,therearesomefeaturesweusewithinthistutorialthatareonlyfoundinUnity2.0andabove.

• BasicScripting.

Weassumethatyoualreadyhaveagraspofbasicscriptingprinciples.

• FamiliaritywiththeUnityuserinterface.

YoushouldalsobefamiliarwithUnity’skeyinterfaceelements,suchastheInspector,thevariousViews,andbasicdrag­and­droptechniques.IfyouareunfamiliarwithUnity,pleasetakealookatour“IntroductiontoUnity”videos.You’llfindtheseinourwebsite’sResourcesarea.

• 3DModelingTools(Recommended).

Althoughnotrequiredsincewesupplythemodels,itisrecommendedthatyouhavetoolstoexaminethe3Dassets.SuchtoolsincludeAutodeskMaya8,3DStudioMax,Cinema4D,andCheetah3D.(NOTE:BlendercanexportFBXfiles,butcannotcurrentlyimportthisformat.)

• 2DGraphicsTools(Recommended)

Again,itisnotrequiredbutwerecommendedthatyouhavetoolstoexaminethe2Dassetswesupply.SuchtoolsmayincludeAdobePhotoshop,CorelPainter,oroneofthebudgetalternativessuchasPixelmator.

Also,besuretodownloadtheprojectfilemeanttoaccompanythistutorial.You’llfindthefilesinourResourcessection:http://unity3d.com/support/resources/

6

Page 7: 2 d Game Play Tutorial

SettingTheScene

ThissectionofthetutorialwillmostlydealwithhowtosetupGameObjectsinthesceneview,addingComponents,andhowtomanipulatethemintheInspector.

Weprovideyouwitharelativelyemptysceneandyourmissionistobuildontothatscenetomakeupamorecompletelevel.Bottomlineis,weareprovidingthetoolsyouneedandyouneedtousethemtoconstructalevel.Lateroninthistutorialwedelveabitdeeperandexplainhowsomeofthespecificscriptswork.

Gettinginthe2DMind­SetNowweneedtogetinthepropermind­setandcreatesomecommonconventionsthatwillremainconsistentthroughoutourproject.Firstweneedtodefineourplaneofmotion.Inotherwords,weneedtorestrictmotiontoonlytwoofthethreedimen­sions,traditionallynamedX,Y,andZ.Todothiswemustspecificallydecidewhichaxis ofmotionwillhavenomovement.

TIP WhenintheSceneViewyoucanrememberwhichcolorcorrelatestowhichaxiswiththesimplemnemonicdevice"RGB=XYZ"

TheusualconventionisfortheX­axistocorrespondtohorizontalmovementrelativetotheobserver,whiletheY­axiscorrespondstoverticalmovement.TheZ­axisthere­forecorrespondstomovementstowardsandawayfromtheobserver­­forourpur­poses,thismeanstheZ­axiscorrespondstomotiontowardsandawayfromourcam­era.

Throughoutthetutoriallet’skeepthefollowinginmind:

7

It’stimetoprepareforourjourney.

InthissectionwestartputtingourscenetogetherandlookathowUnitycanbemadetohandle2Dgames.

Page 8: 2 d Game Play Tutorial

• DefiningourPlaneofMotion.

WearegoingtostickwithcommonconventionandhaveourmotionbeintheX­Yplane,meaningthatnomovementwilloccurintheZ­axis.VerticalmovementwillbeintheY­axisandhorizontalmovementwillbeintheX­axis.

• RestrictedRotation.

Wealsoneedtorestrictourrotation.Asageneralrule,theonlyrotationthatwewillallowisrotationaroundtheZ­axis.RemembertheZ­axispassesthroughthecamera;thereforerotationaroundtheZ­axiswillresultinclockwiseandcounterclockwisero­tationastheMainCameraseesit.Thereisoneexceptiontothisrestrictedrotation,however.Thecharacterisallowedrotationaboutthey­axissohecanturnfromsidetoside.

A2Dgameneedsjusttwoaxes:XandY.

Withallthisinmind,it'sfinallytimetoopenourprojectandscene.Ifyouhaven'tal­readydoneso,pleasedownloadtheprojectfilesnow.

SelectFile­>OpenProjectandlocatethe2DTutorialprojectthatyouhavedown­loaded.

Onceyouhaveopenedtheproject,findthescene2DPlatformerintheProjectPaneandopenit.

PlaytheScene.

8

Page 9: 2 d Game Play Tutorial

The2DPlatformerScene.

ControlsUsethecursorkeystomoveLerpz.HolddowntheCtrlkeytomakehimrunandusethespacebartojump.

TheGUIbuttonsatthetoptogglebetweencontrollingthecharacterandthespace­ship.Everythinginthisscenehasalreadybeenlaidoutforyou.Feelfreetoexploreandexamineeverythingyoucan.Themorefamiliaryouarewithhowwesetupourlevel,theeasieritwillbetocreateyourown.

ACloserLookHerearetwothingsyoucaninvestigatetobetterunderstandhowtosetupa2Dgamebeforeyoudoityourself:

ObjectPositionsIfyoubringupanelementintheInspector,you’llseethatallobjectsareplacedatzerointheZ­axis,keepingtotheconventionwedefinedabove.

Whenmodelingyour3Dassets,itmaymakeyourlifeeasiertomodeltheminyourmodelingapplicationwiththesameorientationasinUnity.Althoughnotcrucial,thisavoidstheinconvenienceofhavingtorotatethemafteryouimportthem.

PlatformTilingIfyouinvestigatetheplatformsinthissceneyou'llnoticethattheyaremadeupofsmaller,tile­ablepieces,withend­capsforthebeginningsandendsofplatforms.ThiscansavehoursofmodelingtimesoplatformscanbebuiltwithinUnityandeasilychanged.Everythingfromthesizetothetexturesaremodeledwithtilinginmind.

9

Page 10: 2 d Game Play Tutorial

NOTE Tilingwasaverycommontechniqueintheearlydaysofcomputergames.Ithadtheveryusefuladvantageofreducingtheamountofgraphicalassetsre­quired,keepingtheproject’soverallsizedown.Inthedayswhencomputermemorywasmeasuredinkilobytes,thiswasanimportantfactor.Today,tilingremainsausefultechniqueasitreducesbothassetproductiontimeanddown­loadsize.

SettingtheLevelAttributesAfterplayingourpre­builtlevel,it'stimetobeginourown.

CreateanewscenebygoingtoFile­>New.Younowhaveacompletelyemptyscenethatisreadytorock.Beforeyoubegin,makesurethatyourinterfaceissetuphowyouprefer.BesurethattheSceneView,ProjectPane,HierarchyPane,andInspectorareallpresent.

FirstthingtodoistodefineourSkybox:

GotoEdit­>RenderSettingsinthemenu.IntheInspector,youshouldseeanemptyslotforaSkybox.

IntheProjectPane,expandthefolderStandardAssets­>Skyboxes.

DragMartianStratosphereintotheSkyboxMaterialslotintheInspectorfortheRenderSettings.

TheRenderSettings

Nowweshouldhaveaniftyskyboxthatwewillseeinthebackgroundatalltimesinourgame.

10

Page 11: 2 d Game Play Tutorial

TheGameView,showingtheSkybox.

Next,weneedtoaddsomethingwhichwillmanagesomeimportantattributes.

LookintheProjectPaneandfindthePrefabnamedLevelAttributeswithintheLevelPrefabsfolder.

DragthePrefabintotheHierarchyPanesoitisloadedinyourscene.

EnsurethatitsPositionisat(0,0,0).Thiswillmakelifeeasierinthelongrunforthechildobject"DeathZone."

TheLevelAttributesPrefabintheSceneView.Weseetwonewobjectshere:thesmallrectanglerisingup­wardsdefinesthelevel’sboundaries.Thelongoblonglyingflatisthe“DeathZone”(displayingtheskull).

11

Page 12: 2 d Game Play Tutorial

IntheSceneViewyoushouldnowbeabletoseeagreenrectanglethatrepresentsthesizeofyourlevel.Ifyoucannotseethegreenrectangle,adjustyourviewingpositionsothatyoucanclearlyseeit.

Adjustthesettingsaccordingtohowbigyouwantyourleveltobe.

Asareferencepoint,thecompletedlevelthatwesuppliedwas44.25unitswideby60unitstall.MakesurethateverythingislocatedatzerointheZ­axis.Thesizeofyourlevelcaneasilybechangedlatersodon’tworryaboutgettingitab­solutelyright.

Finally...

SAVEyourscene!

Sowhat’sgoingonhere?LetstakeamuchcloserlookattheLevelAttributesandDeathZoneGameObjects...

ObjectProfile:LevelAttributesTheLevelAttributesobjectstartedasanemptyGameObjectatposition(0,0,0).ThescriptLevelAttributeshasbeenappliedtoit.

Functions• OnDrawGizmos()

Displaysthelevel’sdimensions.Thelevel’ssizeisdenotedbythegreen­borderedrec­tangledrawninthesceneview.

• Start()

CreatesphysicsCollidersatstartupthatactasbordersaroundtheworldtopreventthecharacterfromleavingthelevelboundaries.

Script:LevelAttributesThisscriptdefinesthelevel’skeyattributesbasedonthevaluesyousetintheInspec­tor:

• Bounds

‣ X:Thex­coordinatethatyourlevelwillstartat.

‣ Y:They­coordinatethatyourlevelwillstartat.

‣ Width:ThewidthofyourlevelstartingattheX­coordinateabove.

‣ Height:TheheightofyourlevelstartingattheY­coordinateabove.

12

Page 13: 2 d Game Play Tutorial

• FallOutBuffer:Thiscreatesabufferzoneatthebottomofyourlevel.ItspurposeistogiveyourcharactersomeroomtofallwithoutthecamerafollowinguntilithitsthebottomCollider.

• ColliderThickness:ThethicknessoftheCollidersthatcreateyourborders.

FurtherAnalysisIfyouselecttheLevelAttributesGameObjectafterpressingplay,thenlookatthegreenboundaryrectangleinthesceneview,youwillnoticeColliders(representedbylightgreenboxes)attheedges.Thesearetheautomatically­generatedphysicsCollid­erscreatedbytheLevelAttributesscript.

ObjectProfile:DeathZoneTheDeathZoneobjectstartedasanemptyGameObjectatposition(0,0,0).ItisachildobjectofLevelAttributes.ItdoesnotneedtobeachildofLevelAttributes,butfororganizationalpurposesworkswellthere.Thescript"DeathTrigger"hasbeenap­pliedtoit.

FunctionProvidesaCollider­­definedasaTrigger­­whichcausesthecharactertore­spawnifhe/shefallsontoit.Thisisusefulforpitsthattheplayercanfallinto.

Script:DeathTriggerThisscriptdrawsthelittleskullandcrossbonesthatyouseeinthesceneviewbytak­ingadvantageofGizmoicons.Althoughit'snotnecessary,itisuseful.(“SettingUpthePlatforms”hasmoreinformationonGizmos.)

SettingUpthePlatformsNowit'stimetocreatethefoundationofourlevel:theplatforms.

IntheProjectPaneyouwillseeaprefabcalled"Pre­AssembledPlatform."DragitintotheScene.

Ensuretheplatformislocatedatzeroalongthez­axis.

Positiontheplatforminaplaceyou'rehappywith.

13

Page 14: 2 d Game Play Tutorial

PlacingthePre­AssembledPlatformPrefab.

Thisplatformwaspre­assembledforyou,butyouwillhavetomaketherestyourself.

LookintheHierarchyPaneandyou'llseethatthePre­AssembledPlatformhasseveralchildobjects.Thesechildrenobjectsarewhatmakeuptheplatform.Ifyouinvestigatetheplatformsyou'llnoticethattheyaremadeupofsmaller,tile­ablepieces,withend­capsforthebeginningsandends:

LookinginsidethePre­AssembledPlatformPrefab.

Usingtheseplatformtiles,createmoreplatformsforyourcharactertorunwild!

Keepthesepointersinmind:

• Alwaysmakesurethez­positionisatzero.

• Lookatthepre­assembledplatformforreference.

14

Page 15: 2 d Game Play Tutorial

• Wehighlyrecommendthatyouparentgroupsofplatformtilestogether,forreasonsdescribedinObjectProfile:Pre­AssembledPlatform,below.

Todothis,createanemptyGameObjectbygoingtoGameObject­>CreateEmptyandnameitappropriately.MakesuretheGameObjectislocatedatzeroalongtheZ­axis.AlsomakesurethattheXandYcoordinatesarewhereyouwanttheplatformtobelocated.ThenyoucandragtheplatformtilesinsidetheemptyGameObjectyoujustcreated.Last,applythescriptCombineChildrensoyoumimicthefunctionofthePre­AssembledPlatformGameObjectdescribedabove.

• Thetilescanbepreciselypositionedeasilybecausetheirlengthsarenicewhole­numbervalues.

• Theplatformsmuststayinsideofthegreenlevelboundaryyousetupintheprevioussection!Ifyourplatformsareoutsidethisareatheywillbeunreachable.Youcanal­wayschangethesizeoftheboundaries.

• Savefrequently!

Youcanalwayscreatemoreplatformslater,butyouatleastwantanareathatthecharactercanrunaround.

ObjectProfile:Platform(Prefabs)IntheProjectPaneyoucanfindtheseprefabsinsideLevelPrefabs/Platforms.

FunctionsThesearethetile­ablepiecesthatmakeupthelargerplatforms.You'llfindfivedif­ferentpieceswithinthePlatformTilesfolder:

• Platform­Level:Alevelpieceofplatformthatis6unitslong.

• Platform­SlopeUp:Apieceofplatformthatslopesupmovingfromlefttoright.Itis3unitslong.

• Platform­SlopeDown:Apieceofplatformthatslopesdownmovingfromlefttoright.Itis3unitslong.

• Platform­EndCapLeft:Thisbelongsattheleftedgeofanarrayofplatformstocapitoff.

• Platform­EndCapRight:Thisbelongsattherightedgeofanarrayofplatformstocapitoff.

15

Page 16: 2 d Game Play Tutorial

Thelengthofthesepieces,(withtheexceptionoftheendcapssinceitisnotneces­sary,)arenicewholenumberssotheycanbepreciselytiledbyeditingthenumbersintheInspector.

Components• BoxCollider

Withoutthis,thecharacterandspaceshipwouldfallrightthroughtheplatform!Thisisneededtophysicallyinteractwiththecharacter.TheBoxCollidersizehasbeenad­justedtofittheplatformtile,otherwiseallsettingsaredefault.Sincetheplatformdoesnotmoveatall,wedonothavetoapplyaRigidbodycomponent.

• Pipeline,MeshFilter,andMaterial:Theseassignthepropermeshandtexturesoitrendersinthescene.

Script:CollisionSoundEffectThefootscriptattachedtoourplayerchecksGameObjectitcomesintocontactwithforthepresenceofthisscriptandplaysthesoundeffectitholds(ifyouhavesetone).Inthiswayourplayercharacter’sfootstepscanbemadetosounddifferentondiffer­entsurfaces­­e.g.ametallicsoundonmetalplatforms;awoodenfootstepsoundonwoodensurfaces,andsoon.

Script:CollisionParticleEffectThisscript,liketheoneabove,providesasimilarserviceforparticleeffects.Theplayer’sfootscriptlookstoseeifwe’vesetaparticleeffectGameObjectandstartsitifso.Thisishowthecharacterraisesthecloudsofdustasherunsaroundtheexamplelevel.

TIP Ifyou'recurious,examinethetexture(whichisthesameforeachtile)toseehowitloops.

ObjectProfile:Pre­AssembledPlatformIt'stheparentobjectthatcontainsplatformtilesthatcreateasinglelargeplatform.

Function:ThisGameObjectservestwopurposes.

• Asacontainerusedtoorganizetheleveland

• Toaidperformance­­seethescriptdescribedbelow.

Itisrecommendedthatyoustructureyourentirelevelusingthismethod.Inotherwords,foreachgroupofplatformtilesthatmakeupalargeplatform,createaparentobjectforthemwiththeCombineChildrenscriptapplied.

16

Page 17: 2 d Game Play Tutorial

Script:CombineChildrenIntheInspectoryoucanseethisscriptwithitsself­explanatoryoptions.Whatthisdoes istakeallofthechildrenGameObjects­­i.e.theplatformtiles­­andcombinetheirmeshessoinsteadofrendering6differentobjects,only1objectisrendered.Thisen­hancesperformance,especiallywhenyoureachalargenumberofplatforms.

TIP ThisscriptactuallycomesintheStandardAssetspackage,whichisshippedwithUnity.

IntroducingLerpz,OurLovelyCharacter

Lerpz,ourzanycharacter,isgettinganxiousforaction!

Letsgetourspawnpointsetupfirst.Thespawnpointiswherethecharacterwillap­pearwhenyoustartthegame.It'sprettysimpletodo,justfollowthesesteps:

CreateanewemptyGameObjectbygoingtoGameObject­>CreateEmpty.Re­nameitto“CharacterSpawnPoint”.

17

Page 18: 2 d Game Play Tutorial

ApplythescripttitledSpawnPointtotheGameObjectyoujustcreated.Thisscriptcreatesthatlittle2DiconofLerpzinsidetheSceneViewsoyoucanseewherethespawnpointis.(ThislittledrawingiscalledaGizmo.TheDeathZonealsohasoneofthesetodisplaytheskull­and­crossbonesicon.)

PositionthespawnpointwhereyouwantLerpztoappear.Makesureitisatz=0withaplatformunderfoot,soheactuallyhasaplacetostandwhenheap­pears.

WhatexactlyisaGizmo?Gizmosareshapes,iconsandothervisualaidsthatappearintheSceneViewsuchaslines,lamps,cameras,andaudiosourcestoassistinvisualdebuggingorlayout.Giz­mosdrawnexclusivelyinthis2DtutorialaretheDeathZone,andCharacterSpawnPoint.

Allittakesisaverysimplescript.Here'sanexampleofthescriptSpawnPointthatisappliedtotheCharacterSpawnPoint:

function OnDrawGizmos(){ Gizmos.DrawIcon(transform.position, "Player Icon.tif");

}

GizmoiconsmustbeplacedintheAssets/Gizmosfolder.

TheLevelAttributesscriptalsotakesadvantageofGizmos:ThegreenborderyouseerepresentingthelevelboundariesisaGizmo.ForacompletereferenceonGizmos,youcanrefertothedocumentation(http://unity3d.com/Documentation/ScriptReference/Gizmos.html).

PlacingLerpzThenextstepistoaddLerpzhimselftoourScene:

DragthePrefab"Character(Lerpz)"inourLevelPrefabsdirectoryintotheScene.Sincewehaveaspawnpointsetup,youcanplacehimanywhereyou'dlike,justaslongashe'ssomewhereintheScene.

Ifit’snotalreadyvisible,bringupourCharacterintheInspectorandopenupthePlatformControllerScriptComponent.NotetheSpawnPointslot:

18

Page 19: 2 d Game Play Tutorial

Character(Lerpz)withnoSpawnPointset.

DragourearlierCharacterSpawnPointobjectintothisslot,soitlookslikethis:

Character(Lerpz)withtheSpawnPointset.

ThenextstepistogettheMainCameratofollowLerpzaround...

DirectingtheCameraAtthemoment,ourmaincamerawillsimplysitwhereitisandpointatwhateverit’saimedat.MuchlikeinamovieorTVproduction,weneedtodirectthecamera­­tellithowtomove,whentodosoandwhatitshouldbeaimedat.Weachievethiswithtwoscripts:

DroptheCameraScrollingscript(fromScripts­>2D­>Camera)ontotheMainCameraGameObject.

DroptheCameraFocusscript(fromthesamelocation)ontotheMainCamera.

Thenextstepistogivethescriptstheinformationtheyneedtowork:

SelecttheMainCameraintheHierarchyPaneandopenuptheCameraFocusscriptComponentintheInspector.

OpentheTargetsgroupandchangeSizeto1.Element0shouldappearbelowit.

DragourCharacter(Lerpz)GameObjectontotheElement0slot.

OpentheTargetButtonNamesgroupandchangeSizeto1.(Again,Element0shouldappear.)

Type“Player”intoElement0’sslot.

19

Page 20: 2 d Game Play Tutorial

Theresultshouldlookliketheimagebelow:

SettinguptheCameraFocusscriptcomponent.

Weshouldnowhaveaworkingcameraandcharacterrunningandjumpingoverourplatforms.

ItwasveryeasytogetthecharacterinthelevelusingPrefabs,butoncloserinspectionLerpzisanythingbutsimple:

ObjectProfile:Character(Lerpz)Lerpzisthemaincharacterofourgame.Hecanwalk,run,jump,andfall.Hemovesaroundourlevelwreakinghavocwhereverhegoes.

Components• Animation

Thiscomponentstoresalistofanimationsforthecharacterthatcanbeaccessedbyscripting.PlatformPlayerAnimation(listedbelow)makesuseofthiscomponentbyac­cessingdifferentanimations.

• CharacterControllerThetraditionalside­scrollingcharactercontrolsaregenerallynotphysicallyrealistic.Thecharactercomestoahaltimmediatelyandturnsonadime,makingitdifficultandimpracticaltouseRigidbodyphysics.Asaresult,weuseanalternatemethodtomovethecharacteraroundbyusingtheCharacterController.Seemoredetailonthiscom­ponentinthedocumentation.(http://unity3d.com/Documentation/Components/class­CharacterController.html)

ScriptApplied:PlatformerControllerThisscriptisacustomscriptmadeforthis2Dtutorial.Thisscript,incooperationwiththeCharacterControllercomponent,isusedtodefineitsphysicalmechanicswithinourworld.Mostoftheadjustablesettingsareself­explanatoryandwewillnotgointomuchdetail,butafewrequiresomefurtherdiscussion:

20

Page 21: 2 d Game Play Tutorial

• SpeedSmoothingHowquicklydoesthecharacterchangespeeds?Forexample,howquicklycanthecharactergofromnotmovingtorunning.Highermeansfaster.

• RotationSmoothingHowfastthecharactervisuallychangesdirections.Itdoesnotaffectthemotion.

• CanControlThissimplystateswhethertheplayercancontrolthecharacter.Thiscanbeturnedoffbyanotherscriptifatanytimeyouwantusertoloseorgaincharactercontrol.Anex­ampleofthisbeingtogglediswhenyoutogglebetweenthespaceshipandtheplayer.

• SpawnPointYoumustdefinethespawnpointbydraggingaTransformobjectintotheslot.Thenthecharacterwillspawnatthatpoint.

Script:PlatformerPlayerAnimationThisscripttakestheanimationslistedintheAnimationComponentandplaysthemattheappropriatetimes.Forexampleitdetectswhenaplayerisonthegroundandmovingatacertainspeed,andthenplaystheappropriateanimationsuchas"run."

Script:PlatformerPushBodiesSincethecharacterisnotaRigidbody,itdoesnotautomaticallyphysicallyinteractwitheverythingaroundit.ThisscriptallowsthecharactertoapplyforcestoRigidbod­iessuchasthecrateswithinthelevel.

ThesettingPushPoweristhestrengthofthepushappliedbythecharacter.

ThePushLayerssettingdetermineswhatlayersthecharactercanactuallypush.Some­times,youmaynotwantaspecificRigidbodytobepushedbythecharacterbutstillinteractphysicallywiththeworldaroundit,soyoucancreatealayerforthatobjectmakesurethatthecharactercannotpushthatlayerwiththissetting.

Script:CameraTargetAttributeThisdefinessomecamerabehaviors,andisalsoappliedtotheSpaceship.Thisscriptismorethoroughlydiscussedinthenextsection.

FurtherAnalysisWehavejustscratchedthesurfaceofexplainingthecharacter.Tofullybenefityou,itwouldbewisetoexamineandexperimentwithallofthescriptsattachedtothechar­actertoseehowtheywork.Wehavesuppliedcommentsinthecodetohelpguideyoualong.

TakeafewmomentstoplayaroundwithLerpz'ssettings.Adjustthedifferentsettingstoseewhattheydo,andifthingsgettoocrazyyoucanalwaysdeletehimfromthesceneandaddanewoneusingthePrefab!

21

Page 22: 2 d Game Play Tutorial

LightingourSceneAtthisstagewehaveourcharacterrunningaroundourScene,butit’sallverydark.Weneedsomelightstomakeeverythingeasierontheeye!

We’lladdtwoDirectionalLights:

CreateanEmptyGameObject.Nameit“MainLights”.(We’llusethistoorganizeourlightsandkeeptheminoneplace.)

CreateaDirectionalLight.(GameObject­>CreateOther­>DirectionalLight).

Renameit“Down­light”.

DragthelightintoourMainLightsobject.

RotateourDown­lightobjecttopointabout60degreesdownwards.

Setitasshownbelow(Intensityisalsochangedfromthedefault,to0.5):

Thelightbluedown­light’ssettings.

Nowwe’llrepeattheprocessagain,butforourup­lighter.Thiswilllighttheunder­sidesoftheplatforms:

CreateaDirectionalLight.(GameObject­>CreateOther­>DirectionalLight).

Renameit“Up­light”.

DragthelightintoourMainLightsobject.

RotateourUp­lighttopointabout60degreesupwards.

Setitasshownbelow(Intensityisagainchangedfromthedefault,to0.5):

22

Color Red Green Blue OpacityLight 184 233 255 100

Page 23: 2 d Game Play Tutorial

Thepurpleup­light’ssettings.

Thenextstepispurelyforourownconvenience:

SelectourMainLightsparentobjectanddragitbackwards,awayfromtheplat­forms(seescreenshotbelow).Precisionisn’timportanthere:thisisjusttokeepthelightsoutofthewaywhilewework­­asthey’reDirectionalLights,theirdistancefromtheplatformshasnoeffect.

Ourcompletedlightingrigshouldlooksomethinglikethis,(althoughyourlevel’splatformswillprobablybeverydifferent):

Ourlights,positionedawayfromourCameraandlevel,sowecanseethemmoreclearly.The“MainLights”objectishighlightedhere,showingboththechildlights.

TIP Thelightcolorschoseninthisexamplearehardlysubtle,buttheyclearlyshowhoweachlightaffectsthescenery.Feelfreetochangethecolors!

23

Color Red Green Blue OpacityLight 238 71 255 100

Page 24: 2 d Game Play Tutorial

SpicinguptheCharacterLerpzhasacoupleofsimplevisualtouches:aworkingjet­packanddustcloudskickedupwhenhewalks.Let’slookattheseinmoredetail:

JetPackParticleEffectsIfyouwatchthecharacter'sjetpackitonlyfireswhenhejumpsandismovingup­wards.Additionalscriptingisneededtoaccomplishthis.Wealsoneedtomakesomeparticleeffects.

IntheHierarchyPane,expandtheCharacter,thenexpandrootJointandlastlyexpandtorso.HereyouwillseewheretheRocketJetGameObjectsarelocated.

ThecodetostartthejetsisinsidethePlatformerControllerscriptwithintheUp-

date()function.

TIP Unity’sParticleSystemfeaturesarecoveredindepthinourResourcesarea.CheckoutForest“Yoggy”Johnson’svideoonthesubject,aswellasour3DPlatformerTutorial.

FootstepsinthedustAsLerpzwalks,wehearhisfootstepsandseehimkickingupplentyofdust.(Clearlyit’sbeensometimesincetheseplatformsweregivenagoodclean!)

IfyouexpandthemanylevelsofLerpz'slegsintheHierarchyPane,you'llnoticethateachfoothasaFootEffectGameObjectattachedtoit.ThiscontainsthreeComponentsandascript:

• RigidBodyThiscomponentisrequiredifwewantUnitytodetectcollisions.

• AudioSourceEssentiallyaplaceholderforafootstepsound.Whenourscriptdetectsthatourfoothasstruckanotherobject,itchecksifthatobjecthasaCollisionSoundEffectscript.Ifitdoes,itgrabsthatsoundeffect,dropsitintothisAudioSourcecomponentandplaysit,addingasubtle,randomvariationtothepitcheachtimeforvariety.

• SphereColliderUnity’sphysicsengineusesthistodeterminewhenthefoothastouchedsomething.Thisissetasatrigger.WhenthisCollidertouchesthecolliderinaplatformobject,thefootscriptreactsaccordinglybyscanningtheobjectwe’vestruckforCollisionSoun­dEffect(seeabove)andCollisionParticleEffectscripts,playingtherelevanteffectsac­cordingly.

Thefootscriptdoesnothingotherthanthetasksmentionedaboveandisthereforeveryshortandsimple:

24

Page 25: 2 d Game Play Tutorial

var baseFootAudioVolume = 1.0;

var soundEffectPitchRandomness = 0.05;

Thesetwovariablesdefinethevolumeofthefootstepsoundeffect,aswellashowmuchvariationisappliedtoitspitch.(Thisvariationisusedtopreventthefootstepsoundingtooartificial.)

ThefirstfunctionwedefineisOnTriggerEnter().Thisiscalledwheneverthe

SphereCollidertouchesanotherCollider,suchasthatattachedtoaplatformelement:

function OnTriggerEnter (other : Collider) { var collisionParticleEffect : CollisionParticleEffect = other.GetComponent(CollisionParticleEffect); if (collisionParticleEffect) {

Instantiate(collisionParticleEffect.effect, transform.position, transform.rotation); }

TheabovecodelooksforaCollisionParticleEffectscriptintheobjectwe’vecollidedwith.Ifitfindsone,itfetchestheparticlesystemPrefabwe’vestoredinthereandin­stantiatesitatthefoot’sposition.Thisishowweproducethelittlecloudsofdust.

Thenextsectionofcodedoessomethingverysimilarforthefootstepsoundeffect:

var collisionSoundEffect : CollisionSoundEffect =

other.GetComponent(CollisionSoundEffect);

if (collisionSoundEffect) { audio.clip = collisionSoundEffect.audioClip; audio.volume = collisionSoundEffect.volumeModifier * baseFootAudioVolume;

audio.pitch = Random.Range(1.0 - soundEffectPitchRandomness, 1.0 + soundEffectPitchRandomness); audio.Play(); }}

Thiscodelooksforafootstepsampleintheobjectwe’vecollidedwith.Ifitfindsone,itgrabsit,copiesitintotheFootEffectGameObject’sownAudioSourcecomponent,addsabitofrandomvariationtoitspitch,thenplaysit.

TheonlyotherfunctioninthisscriptisReset(),whichsimplyensurestwokeyprop­

ertiesaresettothecorrectdefaultvalues.Thisfunctioniscalledautomaticallyby

25

Page 26: 2 d Game Play Tutorial

UnitywhenthescriptisfirstaddedtoaGameObject,anditcanalsobecalledmanu­allybyclickingonthecog­wheelicontotherightofthescriptcomponent’snameintheInspector.

function Reset() {

rigidbody.isKinematic = true; collider.isTrigger = true;}

@script RequireComponent(AudioSource, SphereCollider, Rigidbody)

TheverylastlineinthecodeisaUnitydirectivewhichensuresthethreecomponentslistedarepresentinourGameObject.Thissaveshavingtoremembertoaddthemmanually.

TheCameraIt’snowtimetolookatoperatingtheCamera.Weneedittofollowourplayeraroundthelevel.

SavethesceneyouhavebuiltsofarandreopentheScenenamed2DPlatformerthatcamepre­madewiththistutorial.

PlaytheSceneforamomentandobservethecameramovement.

• Youshouldseethatnotonlydoesthecamerafollowthecharacter,butthecharacter's positionshiftsashewalksfurtherinasingledirection.Thissubtlemovementallowstheplayertomoreeasilyviewwhat'sahead.ThisisatechniquewhichcanbeseeningamesasoldasWilliams’classicarcadegame,“Defender”.

• Inadditiontothisbasicmovement,wealsoaddeda"Springiness"propertytoourcamera’sscript:Whenthecharacterjumps,itispreferablenottohavethecamerafol­lowtheentirejumpingmotionbecauseitmakesforsomejerkycameramovement.Tosolvethisproblem,weprovideasettingthatallowsthecameratolagalittlesoitdoesn'tfolloweverysinglemotion.

• Thethirdandfinalpointtonoteisthecamera’sbehaviorattheboundariesoftheworld.Noticehowthecameradoesnotmovepasttheboundaries.

Havingawell­placedcameraisalmostalwaysdifficultnomatterwhattypeofgameyouaremaking,andthereforecanoftengetcomplicated.Thecameramotionweprovideinthistutorialmaynotbeperfectineveryway,butitisagoodplacetostart.

26

Page 27: 2 d Game Play Tutorial

ObjectProfile:MainCameraThisprovidestheplayer’sviewofourSceneandisanimportantpartofourgame.

Components• Camera

ThisisthecorecomponentforaUnitycamera.ItisacomplexcomponentwhichreliesonthefollowingComponents,(whichUnitywillnormallyaddautomatically):

‣ GUILayerThisallows2DGUIstoberendered.

‣ FlareLayerThisallowslensflareeffectstoberendered.Thesearebeyondthescopeofthistu­torial.

‣ AudioListenerThisisbasicallyamicrophoneattachedtothecamera.Traditionally,themicrophoneisattachedtothecamerabecauseitallowsformorerealisticstereosoundasitrep­resentstheplayer’spointofview.Withoutthiscomponent,wewouldnothearanyaudiowhileplayingourgame.

Script:CameraScrollingThisisthescriptthatmakesthecameramovehowwewant.Thereisn'tmuchtoad­justhereexceptfor:

• DistanceThisisthedistanceinthez­directionthatthecameraisfromthetargetobject.

• SpringinessAswestatedearlier,whenthecharacterjumpsitispreferablenottohavethecamerafollowtheentirejumpingmotionbecauseitmakesforjerkymotion.Thissettingde­fineshowresponsiveourcamerawillbetothetarget'smotion.

Script:CameraFocusThisscriptallowsustoeasilyswitchbetweendifferenttargetsforthecamera.Inourcase,thetargetswillbeLerpzandtheSpaceship.

NOTE ThisscriptalsotakesadvantageofthenewGUIfeaturesinUnity2.0.Inthepre­madescenewehavesetupforyou,thisscriptiswhatallowsyoutotogglebetweentheLerpzandtheSpaceship.

Let’stakealookattheadjustablesettings:

• TargetsYoucansetasmanytargetsasyoulike.Ourpre­assembledscenehastwo.YouneedtodragaTransformobjectfromtheHierarchyintotheslot.

27

Page 28: 2 d Game Play Tutorial

• TargetButtonNamesThisshouldhaveasmanynamesastherearetargets.ThesearethenamesthatappearonthebuttonsoftheGUIdisplaypanel.

FurtherAnalysisWewilltakeacloserlookatthecamerascriptsinthenextsectionofthistutorial.

ContinuingourLevelNowthatwehaveanideawhatcomponentsandscriptsweneed,it’stimetogetthecameraworkinginournewScene...

Reopenyourscene,ifit’snotalreadyopen.

ExperimentwiththeSpringinessandDistancesettingsintheCameraScrollingscript.Setthemaccordingtoyourpreference.

Thereisanothercamera­relatedscriptwhichisnotappliedtothecameraitself.Weneedtoexaminethistoo.ItistheCameraTargetAttributesscript.

ThisscriptisappliedtotheCharacter,andlaterwillbeappliedtotheSpaceship.

ScriptProfile:CameraTargetAttributesProvidesafewadditionalcameramovementpropertiesthataren'tappliedontothecameraitself.

AppliedTo: Character(Lerpz)andSpaceship

KeyProperties

HeightOffsetWhenat0,thetargetwillbesittingverticallyinthecenterofthescreen.Ifitissettoapositivenumber,thatmeansthecamerawillshiftupwards,resultinginaverticallyoff­centertarget.

DistanceModifierThedistanceofthecamerafromthetargetisdefinedintheCameraScrollingscript,butthissettingaddsontothatvalue.Inthepre­assembledscenetherockethasahigherdistancemodifier,sothecamerapullsbackalittlewhenyouchoosetocontrolit.

VelocityLookAheadThisdefineshowquicklythecamerashiftsto"lookahead"whenacharacterismov­ing.

28

Page 29: 2 d Game Play Tutorial

MaxLookAheadThisdistanceiswherethe"lookingahead"willstopsothecharacterdoesn'tleavethescreen.Xrepresentsthehorizontaldistance,Yrepresentstheverticaldistance.

Beforeyoumoveon,playaroundwiththeLerpz'sCameraTargetAttributesset­tingstounderstandwhatthisscriptdoes.

OrthographicProjectionEventhoughweareworkingwith2Dmechanics,thegraphicsarestill3Dandevery­thingstillhasabitofperspectivetoit.Foryoutraditionalistsoutthere,justfollowthesestepssoit'sstrictlyside­vieworthographicwithnoperspective:

IntheHierarchy,selectyourMainCamera,andchecktheboxintheInspectorthatsays"Isorthographic."

IntheGameViewyoushouldseeastrictorthographicviewofyourlevelwithoutper­spective.Butthere'saproblemnow,theSkyboxhasdisappearedbecauseitdoesn'tworkfororthographicviews.Noneedtoworry,afewquickadjustmentsandwe'rebackinbusiness!

AdjustasettingoftheMainCameraintheInspector.Bydefault,thesettingClearFlagsissettoSkyboxbutwewantittobesettoDepthOnly.

Nowweneedtoaddanewcameratorenderthebackdrop.

GotoGameObject­>CreateOther­>Camera.

ThisnewcamerawillbesettoonlyrendertheSkyboxandnothingelse.

ChangetheDepthsettingto"­2",whichsetsittorenderbeforetheMainCam­eraandthereforewillappearinthebackground.

NowtheCullingMasksettingneedstobechangedtoNothing,otherwiseyourlevelmayberenderedmorethanonce.

YoucanalsoadjusttheFieldofViewsothatyoucanseeasmuchoraslittleoftheskyboxasyoudesire.

Nowyouhaveaside­scrollerthathasamoretraditionalfeelwithoutperspective!

HandlingRigidbodiesRigidbodiesarethegatewayforapplyingphysicstoyourobjects.(Ifyouareunfamil­iarwiththeconceptofaRigidbody,pleaseviewthedocumentation.)

OurjobistotelltheRigidbodieshowtobehaveinthisrestrictive2Dplaneofmotion.TheplatformswillnevermovesotheRigidbodycomponentisnotnecessary,butthe

29

Page 30: 2 d Game Play Tutorial

rocketshipandthecratesneedtomoveandphysicallyinteractwiththeirsurround­ings.ThissectionexplainshowtorestrictmotionoftheseRigidbodies.

IfyouweretoexamineboththecrateandtherocketintheInspectorViewofourpre­assembledscene,youwouldnoticetwomajorthingsthatarespecifictoour2Dgame:

• Theyarebothlocatedat0alongtheZ­axis.ThisisimportantbecauseeveryobjectneedstobeatthesameplacealongtheZ­axis.

• Theyalsohaveacomponentcalled"ConfigurableJoint."ThisisanewcomponentinUnity2.0whichofferscountlesspossibilities,butforourpurposesitisusedforrestrict­ingmotion.

NoticethatZMotionislocked,whichdisallowsmotionintheZ­axis.AngularXMotionandAngularYMotionarealsolocked,preventinganyforbiddenrotationsconformingwithwhatwedecidedinthepreviouschapter.TheConfigureInWorldSpacecheck­boxisalsoselected.Allothersettingsareleftattheirdefaultvalues.

Letstakeacloserlookatthecrate.(TheSpaceshiphasadditionalcomponentsadded,andwewilllookatthatlater.)

ObjectProfile:CrateIntheProjectPaneyoucanfindthisprefabinsideofthedirectoryLevelPrefabs.Thecrateisnotmeanttobestationary,butratherinteractwiththecharacterandtheworldaroundit.

Components• BoxCollider

WithouttheBoxCollider,theobjectwouldnotbeabletophysicallyinteractwithitsenvironment.Allofthesettingsherearethedefaultsettings.

• RigidbodyThisalsoallowsthecratetophysicallyinteractwithitsenvironment.Thesettingsherearealsothedefaultvalues,butyoucanadjustthemtomakeitmoremassive,toig­noregravity,ortobeimmovable.

• ConfigurableJointThisisthecomponentthatrestrictsourmovementtoour2Dplane.Allsettingsaredefaultexceptforthefollowingfour:

‣ ZMotion:Locked

‣ AngularXMotion:Locked

30

Page 31: 2 d Game Play Tutorial

‣ AngularYMotion:Locked

‣ ConfigureinWorldSpace:Checked

• Pipeline,MeshFilter,andMaterialTheseassignthepropermeshandtexturesoitrendersinthescene.

Script:CollisionSoundEffectThisscriptassignsasoundforwhenanobjectcollideswithit.Thecollidingobjectmustactivatethesoundthroughscripting.

Thehumblecrate.Soversatile!Soeasytomodel!Wherewouldthegamesindustrybewithoutthem?

ExerciseAddasmanycratestoyoursceneasyouwant.Youcanorientthemhoweveryouwantaslongasthey'relocatedatzeroalongthez­axis.

Afteryouhaveaddedcrates,stepitupbycreatingyourownRigidbodytobeloadedinthescene.

Trycreatingaspherethatthecharactercanrollwhenitispushed.Applythesamecomponentsandsettingstothesphere,butmakesureyouaddaSphereColliderinsteadofaBoxCollider.

Don'tforgettosaveyourscene!

31

Page 32: 2 d Game Play Tutorial

MovingPlatformsAcommoningredientinaside­scrolling2Dgameisamovingplatform.Tocreateamovingplatformwe’regoingtopositiontwowaypointsintheScenethatthemovingplatformwilloscillatebetween.

DroptheMovingPlatformPrefabintoyourscene.

DropaPlatformWayPointPrefabintoyoursceneandpositionitwhereyouwanttheMovingPlatformtostartfrom.

DuplicatethePlatformWayPointandpositionitwhereyouwanttheMovingPlatformtomoveto.

IntheMovingPlatform’sInspectorthereisascriptnamedPlatformMoverwithtwoslots,TargetAandTargetB.DropyourtwoPlatformWayPointGameOb­jectsfromtheHierarchyintotheirrespectiveslotsintheInspector.

ThereisalsoasettingforSpeedwhichcontrolshowfasttheMovingPlatformwillmovebetweenthetwoPlatformWayPoints.

Nowifyouhitplay,theplatformshouldbemovinghowyou'dexpect.Ifitisn'tbehav­ingcorrectly,adjustyourtwoPlatformWayPointsandtheSpeedvariableuntilyouachievethedesiredresult.

TIP Youcanaddasmanymovingplatformsasyou'dlike.EachmovingplatformshouldhaveitsownsetoftwoPlatformWayPointstomovebetween.

32

Page 33: 2 d Game Play Tutorial

ObjectProfile:MovingPlatformDescription:Themovingplatformthatthecharactercanstandon.Themovingplat­forminthepre­assembled2DTutorialscenemovesvertically,buttheycanbemadetomovewhicheverdirectionyoudesire.

Components• BoxCollider

WithouttheBoxCollider,thecharacterandotherobjectswouldfallrightthroughit!

• RigidbodyThisalsoallowsthecratetophysicallyinteractwiththecharacterandotherobjects.Afewsettingsdeviatefromthedefault."UseGravity"settingisoff.The"IsKinematic"settingison.The"IsKinematic"settingpreventsthecharacterorotherRigidbodiesfrommovingtheplatformsomewherebesidesitspredefinedpath.

• ConfigurableJointLiketheRigidbodiesdescribedintheprevioussection,thiscomponentrestrictsourmovement.EverythingisthesameexceptnowALLrotationisforbidden:

‣ ZMotion:Locked

‣ AngularXMotion:Locked

‣ AngularYMotion:Locked

‣ AngularZMotion:Locked

‣ ConfigureinWorldSpace:Checked

33

Page 34: 2 d Game Play Tutorial

• Pipeline,MeshFilter,andMaterialTheseassignthepropermeshandtexturesoitrendersinthescene.

Script:MovingPlatformEffectsThisscriptisusedtoactivatetheparticleeffectsonthebottomoftheplatform.TheHorizontalSpeedtoEnableEmitterspropertydefineshowfasttheplatformneedstomovehorizontallyforthejetstofire.Itautomaticallyfiresforanyverticalmovement.We’lltakeamorein­depthlookatthisscriptlater.

TheSpaceshipBynowyoushouldhavealmosteverythingsetup.Lerpz,thecharacter,shouldbemovingaroundandnavigatingovercratesandmovableplatforms.ThelastthingyouhavetosetupistheSpaceship.AddingaspaceshipinthistutorialwillshowyouhowtoaddforcestoaRigidbodyandmakeitmove.

ThereareonlytwothingsyouneedtodotogettheSpaceshipfullyfunctional:

FirstdragtheSpaceshipPrefabintotheScene.

Positionitwhereyouwantinyourlevel.

NowweneedtoadjustafewsettingsintheMainCamerasothatthecamerawillswitchbetweentheSpaceshipandLerpz.It'stimetorevisittheCameraFocusscript:

ChangethenumberofTargetsto2withElement0asCharacter(Lerpz)andElement1asSpaceship.ThiseasilyachievedbydraggingtherespectiveGameObjectsontothe“Element”slots.

YoualsoneedtochangethesizeofTargetButtonNamesto2,withElements0and1namedPlayerandSpaceshiprespectively.Youcanseethefinalsettingsinthefollowingscreenshot.

Nowyou'regoodtogo!

34

Page 35: 2 d Game Play Tutorial

TheupdatedCameraFocusscriptsettings.

Youshouldbynowhaveacompleteandworkinglevel!Ifanythingisn'tworkingproperly,readbackandseeifyoumissedanything.Alsorememberthatyoucanal­waysopenthescene2DTutorialandusethatasareference.

Don'tforgettosave!

ObjectProfile:SpaceshipTheSpaceshipprefabcanbefoundinthedirectorLevelPrefabs.It'stheSpaceshipyouflyaroundthelevelwith.

Components• MeshCollider

Allowstheobjecttophysicallyinteractwithitssurroundings.ItisimportantthatCon­vexischecked.AconvexMeshColliderisabletomoveinreal­time,otherwiseitistoocomputationallyexpensivetorun.ToseethedefinitionofaConvexMesh,youcanviewthedocumentation(http://unity3d.com/Documentation/Components/class­MeshCollider.html).

• RigidbodyThisalsoallowstheSpaceshiptophysicallyinteractwithitsenvironment.ThesettingsusedarethedefaultsettingswhenyouapplyaRigidbodytoanobject.

• ConfigurableJointThestandardsettingsthatweapplytootherRigidbodiesinthesceneasseenonourcrate:

‣ ZMotion:Locked

35

Page 36: 2 d Game Play Tutorial

‣ AngularXMotion:Locked

‣ AngularYMotion:Locked

‣ ConfigureinWorldSpace:Checked

• Pipeline,MeshFilter,MeshRenderer,andMaterial:Theseassignthepropermeshandtexturesoitrendersinthescene.

Script:SpaceshipSofartheSpaceshipisnotmuchdifferentfromthecrate,butthisscriptiswhatsetsitapartfromaninanimatephysicsobject.

TheSpaceshipscriptdefineshowitmoveswiththeinputfromthekeyboard.Thead­justablesettingsonthescriptare:

• ForwardDirection

• PositionalMovement

• RotationalMovement.

ForbothPositionalandRotationalMovement,you'llseethatthereisamaxspeedand,bydefault,ifthatspeedisexceededthedragdrasticallyincreases,makingitmuchmoredifficulttoaccelerate.

ThesettingCanControlistoggledwiththecamerascriptCameraFocus,soyouneednotworryaboutthatsetting.

WellDone!Congratulations!Youarefinishedwithbuildingyour2Dlevel.Thiswasnoeasytask­­throughoutthetutorialsofaryouhavebeenintroducedtoahandfuloffundamentalconcepts...andsomemoreadvancedconcepts.Here'swhatyoushouldhaveaccom­plishedsofar:

• Learnedhowtorestrictmovementtoa2Dplane;

• Builtyourlevelwithtileableplatforms;

• Setyourlevelboundaries;

• BeenintroducedtoGizmos;

• ExploredthefundamentalsofsettingupaCharacter;

• Exploredthecomplexitiesofsettingupyourcamera;

36

Page 37: 2 d Game Play Tutorial

• Seenhowtomakeastrictorthographiccameraview;

• LearnedhowtoplaceandmakeRigidbodies;

• Usedwaypointsystemtocreatemovingplatforms;

• SetuptheSpaceship.

Takeamomentforadeepbreathandenjoyplayingyourlevel.Then,ifyou'reambi­tiousyoucandiveintothenextchapter.

37

Page 38: 2 d Game Play Tutorial

DelvingDeeper:ScriptingExamples

StudyingtheScriptsTherearealotofscriptswithinthisproject,andwewillonlycoverafewofthemoreimportantones.Fortheoneswedonotcoverinthetutorialtext,youwillseethatthescriptsarethoroughlycommentedsoyoucanwalkthroughthembyyourself.Thesescriptscoverbothbasicandadvancedconcepts,sowhetheryou'renewtoUnityoraseasoneduseryouwillbenefitfromreadingthem.

MovingPlatformParticleEffectsIfyouwatchthemovingplatform,you'llnoticethattheparticleeffectonlyoccurswhenitismovingupwards.ThiseffectwasaccomplishedwiththescriptMovingPlat­formEffects.

Inanutshell,thisscriptcomparesthepreviouspositionwiththecurrentpositionandifit'smovingupwardstheparticleemittersturnon.NotetheusageoftheLateUp-

date()functioninsteadofUpdate()­­thisistostoptheparticleemitterfromre­actingoneframelate.

// We will turn on our special effects when the platform is raising, but if it is moving side// to side, how fast does it have to be moving to cause our special effects to turn on?var horizontalSpeedToEnableEmitters = 1.0;

// A true/false (boolean) variable to keep track of whether or not our special effects are

// currently turned on.private var areEmittersOn : boolean;

38

Nowwe’velearnedhowtheprojectisorganizedandhowtousethetoolsprovided,it’stimetopeerunderthehoodandseehowthesetoolswork.

Page 39: 2 d Game Play Tutorial

// A reference to our other Moving Platform script that is handling all our movement.

// We'll need it to query the current platform velocity for our special effects.private var movingPlatform : MovingPlatform;

// We are going to use these later to calculate the current velocity.private var oldPosition : Vector3;

private var currentVelocity : Vector3;

function Start() { // Grabs the initial position of the platform. oldPosition = transform.position;

}

function Update() { // Remember if our emitters were on, then we'll see if they are currently on. wereEmittersOn = areEmittersOn;

// The emitters are on if the vertical (y) velocity is greater than 0 (positive), or if the // horizontal velocity in either direction (positive or negative speed) is greater than // our horizontalSpeedToEnableEmitters threshold. areEmittersOn = (currentVelocity.y > 0) || (Mathf.Abs(currentVelocity.x) >

horizontalSpeedToEnableEmitters); // We only have to update the particle emitters if the state of them has changed. // This saves needless computation. if (wereEmittersOn != areEmittersOn) {

// Get every child ParticleEmitter in the moving platform. for (var emitter in GetComponentsInChildren(ParticleEmitter)) { //Simply set them to emit or not emit depending on the value of areEmittersOn emitter.emit = areEmittersOn;

} }}

function LateUpdate () { currentVelocity = transform.position - oldPosition; oldPosition = transform.position;}

// This line tells Unity to nicely place this script in a submenu of the Component menu.@script AddComponentMenu("2D Platformer/Moving Platform/Moving Platform Effects")

39

Page 40: 2 d Game Play Tutorial

TheCameraScrollingScriptNowletsexaminehowwegetthecameratofollowthecharacter.Toaccomplishthisweusescripting.Asimpleyetfunctionalcamerascriptcouldbeappliedtothemaincamera,readthecharacter'sXandYcoordinates,andusethosevaluesforitsownpo­sitionwhilekeepingacertaindistanceawayintheZ­axis.Thisworksperfectlywell,butifyoucloselyexaminepopularside­scrollinggamesyou'llnoticethatit'sneverquitethatsimple:thereareahandfulofsubtletouchestobemadeinordertogeteffectivecamerascrolling.

AllofthismovementisdefinedinCameraScrollingfoundinScripts­>2D­>Camera.Openthescriptandexamineit.Usethecommentswesuppliedtounderstandhowitworks.Herewewillbrieflydescribewhateachfunctiondoes:

• SetTarget()

Lookatthetopofthescriptandyou'llnoticeaprivatevariablecalledtarget.TheSetTarget()functionisusedbyotherscriptstochangetheprivatevariabletarget.Morespecifically,theCameraFocusscriptusesthisfunctionwhenyouclickonthebut­tonsatthetopofthescreentochoosewhethertocontrolLerpzorhisspaceship.

Whynotallowsettingofthevariabledirectly?Simple:thiswaywecanensurethatthevariableisalwayssetbycallingourSetTarget()functions,makingiteasierto

checkthatthevaluewe’resettingittoisavalidoneforourpurposes.

NotealsothatwedefinetheSetTarget()functionmorethanonce.Eachdefinitionacceptsadifferentnumberofarguments(otherwiseUnitywillcomplain).WecanusethesemultipledefinitionsasaneasywaytodefaultthesecondargumenttoFALSEandalsotomakeourscriptseasiertofollow.(Thisprogrammingtechniqueismostcommonlyreferredtoas“Overloading”.)

• GetTarget()

Thisisasimpleaccessorfunction,(sometimescalleda"getter").Itisapubliclycallablefunctionthatreturnsaprivatevariable.Noticehowtarget,definedatthetopofthescript,ismarked"private"?Wecannotaccessitdirectlyfromanotherscript,butan­otherscriptcanaccessthisfunction.

Functionslikethisenforceaconceptcalled“encapsulation”.InUnity,thismeansourscriptiscompletelyself­contained.Otherscriptsdon’tneedtoknowhowitworksin­ternallyandthishelpsusreducebugs,aswellasmakingourscriptseasiertore­useinotherprojects.

• LateUpdate()

We'reusingLateUpdate()insteadofUpdate()toensurethatthecameraisn't

40

Page 41: 2 d Game Play Tutorial

laggingaframebehindofthemotion.ThisfunctionusesthefunctionGetGoalPo-

sition()tointerpolatebetweenthecurrentcamerapositionandthegoalposition.

• GetGoalPosition()

Thisfunctioncalculateswherethecamerashouldbewhenthenextframeisdrawn.

(Thispartofourscriptseemsfairlylong­winded,butmuchofitdealswithhowthecamerabehavesattheboundariesofthelevel,whichinvolvesperformingsimilar,butnotidentical,testsforeachedge.)

StreamlineYourWorkflowAnimportantconcepttokeepinmindforanyprojectishowtooptimizeyourwork­flow.

Onewaytooptimizeyourworkflowisincludedwithinthistutorial.ByharnessingtheflexibilityofUnity,youcancreatescriptsthatautomatecertainproceduresforyou.Morespecifically,inthistutorialyou'llnoticeamenuatthetopofthescreentitled"2D"thatcontainstwoitemsthatautomatetheprocesswejustdescribed.

GiveoneofthesemenuitemsatrybydraggingacrateprefabintotheSceneView.

SelectthecrateintheSceneView,goto2D­>MoveOnto2DPlane.Ifitwasn'talready,you'llnoticethatthecrate'sZ­positionhaschangedtozero.

TheothermenuitemisnotnecessaryforthecratesincethatprefabalreadyhastheRigidbody(andotherrequiredcomponents)attached.

Creatingcustommenucommandscanbesurprisinglysimple!Belowweexplainthescriptusedtocreatethesemenuitems.Thescriptbelow,titledTwoDHelpercanbefoundintheProjectPanewithintheEditorfolder.

NOTE ScriptsthataddcustommenuitemsmustbelocatedintheEditorfolder.

Firstup,wehavethe2Dmenu’sMoveOnto2DPlanefunction.

Thismenuitemhastwofunctions:MoveOnto2DPlane()itself,whichperformsthe

functionwewant;andValidateMoveOnto2DPlane(),whichtellstheUnityEdi­

torwhentoenablethemenuitem.(Notallmenucommandswillneedthelatterfunc­tion.)

@MenuItem ("2D/Move Onto 2D Plane ^2")static function MoveOnto2DPlane () { for (var transform in Selection.transforms) {

transform.position.z = 0; }

41

Page 42: 2 d Game Play Tutorial

}

@MenuItem ("2D/Move Onto 2D Plane ^2", true)static function ValidateMoveOnto2DPlane () { return (Selection.activeTransform != null);}

ThevalidationfunctionmerelychecksthatwehaveaGameObjectselected.(Weactu­allycheckifthecurrentlyselectedobjecthasaTransformasallGameObjectshaveoneoftheseComponents.)

Thesecondmenuitemperformsthesamemove­to­2D­planeactionbycallingMoveOnto2DPlane()first,thengoesaheadandaddstheRigidBodyandConfigur­

ableJointComponentsweneedforaGameObjecttoworkinour2Dgame.ItevenensurestheConfigurableJointComponent’szMotion,angularXMotionandangu­larYMotionpropertiesaresetto“Locked”forus.

NOTE BothourmenucommandswillloopthroughwhateverGameObjectwe’vese­lectedandapplythesameinstructionsonanychildGameObjectsitcontains.

@MenuItem ("2D/Make Selection 2D Rigidbody")static function MakeSelection2DRigidbody () {

MoveOnto2DPlane(); for (var transform in Selection.transforms) { var Rigidbody : Rigidbody = transform.GetComponent(Rigidbody);

if (!Rigidbody) transform.gameObject.AddComponent(Rigidbody); var configurableJoint : ConfigurableJoint = transform.GetComponent(ConfigurableJoint);

if (!configurableJoint) configurableJoint = transform.gameObject.AddComponent(ConfigurableJoint);

//configurableJoint.configuredInWorldSpace = true; configurableJoint.xMotion = ConfigurableJointMotion.Free; configurableJoint.yMotion = ConfigurableJointMotion.Free; configurableJoint.zMotion = ConfigurableJointMotion.Locked; configurableJoint.angularXMotion = ConfigurableJointMotion.Locked;

configurableJoint.angularYMotion = ConfigurableJointMotion.Locked; configurableJoint.angularZMotion = ConfigurableJointMotion.Free;

42

Page 43: 2 d Game Play Tutorial

} }

@MenuItem ("2D/Make Selection 2D Rigidbody", true)static function ValidateMakeSelection2DRigidbody () { return (Selection.activeTransform != null);}

SpaceshipScriptPart1:DefiningHelperClassesThenextscriptwewillbeexaminingiscalledSpaceshipandcanbefoundinthePro­jectPaneinScripts­>2D­>Spaceship.Forthesakeofsavingspacetheentirescriptwillnotbelistedinthistext,butcanbeexaminedonyourownbyusingthecommentsweprovidethroughout.

Whilethespaceshipisselectedinthehierarchy,lookintheInspectorattheSpaceshipcomponent.

NoticethePositionalMovementsettingsandRotationalMovementsettingsareiden­tical.TheybothhaveMaxSpeed,NegativeAcceleration,DragWhileCoasting,etc.

Sincethesesettingsareidentical,thisisaperfectopportunitytocreateahelperclass.

Ifusedcorrectly,ahelperclasscanbeusedtocreatemuchcleanerandreusablecode.Youwillseelaterwhereandhowweusethisclass,butfornowwewilljustdefineit.

(AnotheradvantagetodefiningahelperclasssuchasthisisitspropertieswillbegroupedtogetherbytheInspector,makingforamuchcleanerinterface.)

...class MovementSettings { var maxSpeed : float;

var positiveAcceleration : float; var negativeAcceleration : float; var dragWhileCoasting : float; var dragWhileBeyondMaxSpeed : float; var dragWhileAcceleratingNormally : float;

//A function that determines which drag variable to use. function ComputeDrag(input : float, velocity : Vector3) { var drag = 0.0;

//Is the input not zero (the 0.01 allows for some error since we're working with floats) //If the input is zero, use dragWhileCoasting if (Mathf.Abs(input) > 0.01) { //Are we greater or less than our max speed? and assign the appropriate

drag

43

Page 44: 2 d Game Play Tutorial

if (velocity.magnitude > maxSpeed) drag = dragWhileBeyondMaxSpeed;

else drag = dragWhileAcceleratingNormally; } else drag = dragWhileCoasting;

return drag; }}

ThefunctionComputeDrag()definedintheMovementSettingsclassabovewillbe

usedlaterinthescript.Computingthedragisthesameforbothangularandposi­tionalmovement,soputtingitinthehelperclassmeanswedon'thavetowritethesamecodetwicewhendeterminingwhichdragtouse.

Nextwewilldefineonemorehelperclasstouselaterforaddingparticleeffectstothespaceship.Thisoneisabitshorterandsweeter.

//...continued from Spaceship

//Generally always need this next line for your helper classes.

@script System.Serializableclass SpecialEffects { var positiveThrustEffect : GameObject; var negativeThrustEffect : GameObject; var positiveTurnEffect : GameObject;

var negativeTurnEffect : GameObject; var collisionVolume = 0.01;}

SpaceshipScriptPart2:ControllingtheSpaceshipThenextchunkofcodeshownbelowissimplydefiningourvariablesthatwillshowupintheInspector.

We'reputtingourMovementSettingshelperclassintogooduse.Wedefinebothpo­sitionalSettingsandrotationalSettingsasaMovementSettingsclasstype.

//...continued from Spaceship //What is our forward direction? Our spaceship moves in the positive y direction.

var forwardDirection : Vector3 = Vector3(0.0, 1.0, 0.0);

//We create two instances using our MovementSettings helper class.

44

Page 45: 2 d Game Play Tutorial

//One will be for translational (position) movement, the other for rotational.var positionalMovement : MovementSettings;

var rotationalMovement : MovementSettings;

//We create an instance using our SpecialEffects helper class.var specialEffects : SpecialEffects;

Nowwefinallygettotheheartofthescript.Abovewehavedefinedeverythingthatweneed,andnowweputthoseitemstouse.

//...continued from Spaceship

//FixedUpdate() is advantageous over Update() for working with Rigidbody physics.function FixedUpdate() { // Retrieve input. Note the use of GetAxisRaw(), which in this case helps responsiveness of the controls.

// GetAxisRaw() bypasses Unity's builtin control smoothing. thrust = Input.GetAxisRaw("Vertical"); turn = Input.GetAxisRaw("Horizontal");

//Use the MovementSettings class to determine which drag constant should be used

for the positional movement. //Remember the MovementSettings class is a helper class we defined ourselves. See the top of this script. Rigidbody.drag = positionalMovement.ComputeDrag(thrust, Rigidbody.velocity); //Then determine which drag constant should be used for the angular movement.

Rigidbody.angularDrag = rotationalMovement.ComputeDrag(turn, Rigidbody.angularVelocity);

//Determines which direction the positional and rotational motion is occurring, and then modifies thrust/turn with //the given accelerations.

//If you are not familiar with the ?: conditional, it is basically shorthand for an "if...else" statement pair. See //http://www.javascriptkit.com/jsref/conditionals.shtml thrust *= (thrust > 0.0) ? positionalMovement.positiveAcceleration : positionalMovement.negativeAcceleration;

turn *= (turn > 0.0) ? rotationalMovement.positiveAcceleration : rotationalMovement.negativeAcceleration;

// Add torque and force to the Rigidbody. Torque will rotate the body and force will move it.

// Always modify your forces by Time.deltaTime in FixedUpdate(), so if you ever need to change your Time.fixedTime // setting, your setup won't break. Rigidbody.AddRelativeTorque(Vector3(0.0, 0.0, -1.0) * turn * Time.deltaTime, ForceMode.VelocityChange);

Rigidbody.AddRelativeForce(forwardDirection * thrust * Time.deltaTime, ForceMode.VelocityChange);

45

Page 46: 2 d Game Play Tutorial

}

// The Reset() function is called by Unity when you first add a script, and when you choose Reset on the// gear popup menu for the script.

Next,wedefinesomedefaultvaluesthatappearifyouchooseResetintheInspector.

//...continued from Spaceship

// The Reset() function is called by Unity when you first add a script, and when you choose Reset on the// gear popup menu for the script.function Reset() { // Set some nice default values for our MovementSettings.

// Of course, it is always best to tweak these for your specific game.

positionalMovement.maxSpeed = 3.0; positionalMovement.dragWhileCoasting = 3.0; positionalMovement.dragWhileBeyondMaxSpeed = 4.0;

positionalMovement.dragWhileAcceleratingNormally = 0.01; positionalMovement.positiveAcceleration = 50.0; // By default, we don't have reverse thrusters. positionalMovement.negativeAcceleration = 0.0;

rotationalMovement.maxSpeed = 2.0; rotationalMovement.dragWhileCoasting = 32.0; rotationalMovement.dragWhileBeyondMaxSpeed = 16.0; rotationalMovement.dragWhileAcceleratingNormally = 0.1; // For rotation, acceleration is usually the same in both directions.

// It could make for interesting unique gameplay if it were significantly // different, however! rotationalMovement.positiveAcceleration = 50.0; rotationalMovement.negativeAcceleration = 50.0;}

Last,wetellUnitywhichcomponentsareneededwhenthisscriptisattached.Thisisactuallyfoundattheverybottomofthescript.Itisnotrequiredtobeatthebottom,butforthesakeofconsistencyyouwillnoticethateverytimeRequireCompo-

nent()isusedinourscriptsitisatthebottom.

//...continued from Spaceship

// In order for this script to work, the object its applied to must have a Rigidbody and AudioSource component.

46

Page 47: 2 d Game Play Tutorial

// This tells Unity to always have the components when this script is attached.@script RequireComponent(Rigidbody, AudioSource)

SpaceshipScriptPart3:SpecialEffectsWiththescriptabove,wehaveafullyfunctionalspaceshipthatiscontrolledbytheplayer.However,togiveitalittlemoremojowewanttoaddsomespecialeffects.

TheremainingsectionsoftheSpaceshipscriptdealwiththespecialeffects.

Briefly,alltheparticleeffectsaretakencareofwithintheUpdate()function.Itends upbeingpartitionednicelysinceallofthephysicsandcontrolsaretakencareofwithintheFixedUpdate()function.

ThesoundeffectsareexecutedwiththeOnCollisionEnter()function.

Readthroughthescripttounderstandhowitworks,usingthecommentsweincludedtoassistyou.

NOTE Thespaceshipcurrentlyhasonlyoneparticleeffectthatoccurswhenforwardthrustisoccurring,butthescriptallowsforparticleeffectsinalldirections.Thisisagoodexampleofreusablecodeforvariousdifferentpurposes.

Asanexercise,wesuggestaddingmoreparticleeffectsforthrustintheotherdirec­tions.

Finished!Ifyouhavereachedtheendofthissectionyoushouldbeproud.Youdidn'treallyaddmuchtoyourlevelinthissection,butyoudidexpandyourknowledgebase.Youcanusesomeofthetoolsandconceptsyoulearnedhereandapplythemtocountlessotherprojects.Evenifyoudidn'tcompletelygraspallofthescripts,that'sokay­­juststorethisprojectawayandkeepthesescriptsinmindtouseasaresourcelateron.

Now,propyourfeetonthedeskandenjoyanicetallglassofbeerlemonade­­you'veearnedit.

(Disclaimer:UnityTechnologiesandGraveckInteractivedonotcondonedrinkingonthejoboranyotherinappropriateorillegalalcoholicconsumption.)

47

Page 48: 2 d Game Play Tutorial

What'sNext?

YourTurnInthistutorialwehavelookedintothebasicsofbuilding2Dgamesusing3Dtools.Nowit’stimetotakeoffthoselittlestabilizingwheelsfromthebicycleofwisdomandrideoffonourown!Herearesomesuggestions...

Improvethegame’sUIAtthemoment,theonlywaytoswitchbetweenLerpzandtheSpaceshipisbyclickingonabuttonwiththemouse.Thisbreaksthecontinuityofthegameworldbyrequir­ingtheuseofacompletelydifferentinputdevice.Therearetwopossiblesolutionstothis:

Usethekeyboardinstead.

ReplacetheGUIwithakeyboardcommandtotogglebetweenLerpzandtheSpaceship.(AddingandchangingcontrolsinUnityiscoveredintheUserGuide.)

AllowLerpztoentertheSpaceship.

HavethecontrolautomaticallyswitchtotheSpaceshipwhenLerpztouchesit.ThetrickypartistomakeitlookasifLerpzhassteppedinside­­you’llneedtohidetheCharacter(Lerpz)modelwhiletheSpaceshipisbeingcontrolled.

You’llalsoneedtoaddawaytoexittheSpaceship­­perhapsbyhavingLerpzreappearwhenitlands,orbyaddinganewkeyboardcommand.

48

Hereareafewchallengeswegiveyoutomakethis2Dplatformgamemorecomplete.

Page 49: 2 d Game Play Tutorial

AddsomeblingWhatside­scrollingplatformerwouldbecompletewithoutsomesortofcoin,ring,orothersortofbling.

Here'sastartingpointifyouneedit:

Createanobject(acylinderperhaps)thathasRigidbodyandCollidercompo­nents.

Don'tforgettoapplytheusual2Drestrictions.

Onemethodofcompletingthistaskwouldbetohavetheblingbeatrigger.Whenthecharacterhitsthetrigger,amessageissentfromthecharactertotheobjectthatinturntriggersforces/torquetomakeitspinandflyoffthescreen.

Ifyou'rereallyambitiousyoucouldhaveittriggersoundandparticleeffects.

AddmorepizzazztothespaceshipCurrently,thespaceshiphasoneparticleeffectfortheforwardthrust.Tryaddingparticleeffectsforturningthespaceship.Thiswillbegoodpracticeworkingwithpar­ticleeffects.Don'tjustreusethesameflameeffect­­experimentandchangeitupalittle!Additionally,youcouldhavethespaceshipthrustbackwards.Thisentiretaskrequiresnoadditionalscripting!

HavetheDeathZonere­spawntheSpaceshipLookthroughthescriptstoexplorehowthecharacterisre­spawnedandapplythesamemethodtotheSpaceshipthroughscripting.

TurnitintoagameLerpzdoesn’treallyhaveagoalatthemoment.Thistutorialwasdesignedtoeducateandhasn’tdippedintogamedesignissues.Considerthetutorialasastartingpointandtrymakingacompletegamewithit!Addsomeenemiestofight,puzzlestotosolveandalltheothertrappingsofaplatformer.

49