版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
FPS游戲Part1Introduction第一部ThistutorialwilldetailhowtomakeasimpleFirst Shooter(FPS).Itwillintroducefundamental3DgameprogrammingconceptsandgivetipsonhowtothinklikeagameSettingupthegameenvironment安裝游戲Oncetheassetshavebeenimported,you’llnoticetherearemanyfoldersintheProject一旦資源被導入,你將注意到項目面板上有許在項目面板上,從Objects/mainLevelMesh/mainLevelMesh中選擇IntheInspectorpanel,insideoftheFBXImporteroptionsyou’llfindthe"GenerateColliders"option.Togglethatoptionon.Ifwedon’tdothis,the yerwillsimplyfallthroughthelevel(noDragthemainLevelMeshintothe拖拽mainLevelMesh到場Thereisnoneedtoaddalighttothescene,thelevelisalreadyfullylightmapped.Theimportedleveluseslightmapsforalllightingwhichallowsustouseprebakedshadows.使用prebakedShadows預焙陰影。Lightmapsareverygoodforperformance,especiallyifyouwanttocreateacomplexlightingsetup.光影執(zhí)行起來非常好,尤其是你想建立一個復雜的燈光設置的You’renowreadytoaddacharacterintothe你現(xiàn)在準備要給環(huán)境中增加一個特AddingtheMainCharacter增加主要的特We’renowgoingtoaddinacharacterfor yertocontrol.Unityhasabuiltprefabspecificallyforafirst controller.ThiscanbefoundintheProjectpanelunderStandardAssets>Prefabs.人稱控制器,它能在項目面板的StandardAssets>Prefabs下面ToaddtheFirst Controller,clickonthearrowbesideStandardAssetsintheProjectpanel,aslistofassetswillappear.FindthefoldercalledPrefabsandclickonthearrowinthelefthandside.YoushouldnowseetheFirst controllerasset.DragthisintotheSceneview.為了增加第一人稱控制器,單擊項目面板上的StandardAssets,所有的資源將被列出,發(fā)現(xiàn)Youshouldseeacylinderobjectrepresenting yer,3largearrowsforthelocationin3Dspacefortheobject(ifyoudonotsee3arrowspressthe‘W’key),andawhitemeshwhichshowstheobject’sviewport(whereitiscurrentlylooking).TheFPSControllerisnowthedefaultcamera,bymovingthisobject,youchangethecurrentviewintheGameView.You’llalsonoticethattheFPSControllerhasacameraiconontopofit.Movethecharactersothatitisabovegroundlevelintheenvironment.用來在環(huán)境繞場地的。AswenolongerhaveanyneedfortheMainCamera,youcandelete因為主照相機我們不再需要它了,所以你可以刪 y,youshouldnowbeabletomovearoundthelevelbyusingthemouseandkeyboard(cursorkeystomoveorW,A,S,D).按下“y”,你可以使用鼠標和鍵盤圍繞場地移動(鼠標鍵移動和按“W”、“A”、“S”You’venowcreatedaverysimpleFPS,let’sgive yera你現(xiàn)在建立了一個非常簡單的FPS,讓我們給游戲者一Addingaweapon增加一We’renowgoingtogivethe yeragrenadetypeobjecttothrowintheenvironment.Todothis,you’llneedtocreatesomeJavascriptto lUnityaboutthebehavioroftheweapon.Sowhatdowewanttodo?Wewanttoallowthe yertoshootwhereverthecameraispointing.However,let’sfirstthinkaboutourgamecharacterandtheirweapons.Ourgamecharacterisseenthroughthefirst view,withthecamerapositionedateyelevel.Ifthe yerfiresaweapons,theweaponshouldbelaunchedfromwherevertheirhandsare,notfromeyelevel.Thismeanswehavetoaddinagameobjecttorepresentthegrenadelauncher,and ceitwherethe yer’shandwouldbewhentheyholdthisweapons.Thisensuresthattheobjectfiresfromthecorrectlocation.Createtheweaponlauncher建立一個發(fā)射First,let’saddinagameobjecttorepresentthegrenadelauncher.Agameobjectisanyiteminthe3Dworld( yer,level,sounds),componentsarethepropertiesthatthegameobjecthas.Thereforeyouapplycomponentstogameobjects.首先,讓我們增加一個游戲?qū)ο笠员硎景l(fā)射者。一個游戲?qū)ο笫?D世界中的任何一個事項(游戲者、層面、聲音)Fromthemain selectGameObject>CreateEmpty,andrenametheobjectto"Launcher"intheHierarchypanel.Note,thisobjectisinvisibleasitisandemptyhoweveritisjust ceholderforourmissile從主菜單上選擇GameObject>CreateEmpty,并且在層次面板上重命名對象為Nowlet’sgetinclosetoourFPScontrollersowecanseewheretopositiontheweaponlauncher.現(xiàn)在讓我們關閉FPS控制器以便我們能看到發(fā)射者的位SelecttheFPScontrollerintheHierarchyPanelandensuringthatyourcursorisovertheSceneView,press‘F’(frameselected).Thisfocusesusonthe yer(thecurrentlyselecteditem).NowselecttheLauncherfromtheHierarchyPanelandchooseGameObject>Movetoviewfromthemain .NoticehowtheLauncherobjectisnow cedneartheFPSController.Wecannowusethehandlesto cethelauncherapproxima ywherethehandsshouldbe.現(xiàn)在在層次面板上選擇發(fā)射者并且選擇GameObject>Movetoviewfromthemain ,意發(fā)射者對象是怎么被定為到靠近FPS控制器的。我們現(xiàn)在能使用手柄大概定位發(fā)射者到手柄使用的地方。NOTEYoucanmakethecharacterleftorright-handedbyalteringthelocationofthisobject,noneedtochangeanycode.意你可以通過改變這個對象的向左或向右的特性以改變對象的定位而沒有必要改變?nèi)蜯akesureyourUnitywindowlayoutisin2by3mode(Window>Layouts>2by3),andpressthe ybutton.MakesureLauncherisselectedintheHierarchyViewandwhilstwatchingtheSceneView,movethecharacteraround.You’llnoticethatourlauncherobjectdoesnotmovewithourcharacter(youcanpress ytostopthegamerunningnow).確保你的Unity窗口布局是2by3模式(WindowLayouts2by3),并且按下運行按鈕。確保TosolvethisproblemdragtheLauncherobjectontotheMainCameraobjectthatbelongstotheFPSControllerintheHierarchypanel.ItisokaytobreakthePrefabconnection.NowrunthegameagainandwatchtheSceneView,theLaunchershouldnowmovewithourcharacter.WehaveassociatedtheLaunchergameobjectwithanobjectthatmovesinall3axes(thecamera).CreatetheMissileobject建立一 對Let’screatethemissilethatwillbelaunchedwhentheuserclicksthefireFornowwe’llusesomethingsimple,asphere.CreateanewprefabobjectbyclickingAssets>Create>Prefabfromthe bar,andrenameitto眼下使用一些簡單物體,一個球(sphere),建立一個預制物體對象在Unity菜單條上單擊AssetsCreate>Prefab,并且重命名它為MissileNowcreateasphere(GameObject>CreateOther現(xiàn)在建立一個球(GameObject>CreateOtherNowdragtheSpheregameobjectfromtheHierarchyPanelontotheMissileprefabintheProjectPanel.Theiconfortheprefabwillnowchange.YoucandeletetheSphereobjectfromtheHierarchyView.現(xiàn)在從層次面板上拖拽球游戲?qū)ο蟮巾椖棵姘迳系膍issile預制物體(prefab)中,預制物體的圖標將被改變。你可以從層次面板上刪除球?qū)ο蟆?Anygameobjectwhichyouknowyou’llneedtoinstantiateatruntimeShouldbeaWritetheMissileLaunchercode寫發(fā)射者代TheFPSControllerisaprefabconsistingofseveralgameobjectandcomponents.TheFPSControlleritselfisacylindricalmeshthatonlyrotatesaroundthey-axis,soifweattachthelaunchercode(script)tothis,thenwewon’tbeabletoshootupanddown.Therefore,we’regoingtoattachourlaunchercodetotheMainCamerainsidetheFPSControllerasthecameracanlookinanydirection.擊,因此我們的發(fā)射者代碼附著到了FPS控制器內(nèi)的主照相機上,作為照相機可以看任Let’screateourfirstJavascriptcodewhichwilldescribethebehaviourofthe讓我們建立我們的第一個用來描述發(fā)射者行為的Javascript代SelectAssets>Create>JavaScript,whichcreatesablankJavascript .AnewassetappearsintheProjectPanelentitledNewBehaviourScript.Renamethisscriptto選擇AssetsCreate>JavaScript,用來建立一個空白的Javascript文檔,一個新的名為能指定你想在Unity中使用的擴展的代碼編輯器,通過單擊Unity>Preferences然后選擇theExternalScriptEditorboxCreateanewdirectoryinsideyourProjectViewcalledWeaponScripts,we’llputallourweaponsscriptsinhere.MoveyourMissileLauncherjavascriptintohere,andmovetheMissileprefabalso. 這,的MissileLauncherjavascript遷移到這里,并且預制物體也這樣移動。Let’shavealookatthecompleteJavascriptforMissileLauncher.Youcantypeinthecodesectionsasyoufollow.ThinkingfromahighlevelwhatdowewanttodoWell,wewanttodetectwhentheuserhashitthefirebutton,theninstantiateanewmissile,andlaunchitwithacertainvelocitytowardswheretheuserwasaiming.Let’sexaminethecodeindetail:varvarprojectile:Rigidbody;varspeed=20;function{Thisisthebeginningofthescript,whichdefinestopropertiesanddeclaresafunctioncalledUpdate.這是的開始部分,在這里定義了一些屬性和一個叫Update的函if(Input.GetButtonDown("Fire1")Firstwewanttocheckwhentheuserhitsthefirebutton."Fire1"ismappedtoboththeleftmousebuttonandthecurrentkeyboardconfiguration(thiscanbeeditedfromEditor>ProjectSettings配置上(這可以通過菜單Editor>ProjectSettings>Input編輯){{varinstantiatedProjectile:Rigidbody=Instantiate(projectile,transform.position,transform.rotation);Wedeclareavariabletoholdareferencetotheinstantiatedobject.ThetypeofthisvariableisRigidbody,thisisbecausethemissileshouldhavephysicsbehavior.我們?yōu)榱顺跏蓟瘜ο笠粋€控制參照變量,這個類型是Rigidbody(剛體類型),這時因為這個有一些物理特性和行為。ToinstantiateanobjectinUnityweusetheInstantiatefunctionwiththreeparameters,theobjecttoinstantiate,the3Dpositionitshouldbecreatedat,andtherotationtheobjectshouldhave.Thereisalsoanotherconstructor,checktheAPIguide,butwe’llusethisonefornow.在Unity中初始化一個對象我們使用帶三個參數(shù)的Instantiate函數(shù),這個對象被初始化后,用這個函數(shù)初始化它的3D位置,并且轉(zhuǎn)動這個對象。這里也有另外一個構造器,參考檢查API指南,但我們現(xiàn)在將用這個。Thefirstparameter,projectile,istheobjectwewanttocreate.Sowhatisprojectileanyway?Theprojectileissetbyyouinsidetheeditor.Toallowthistohappen,wedeclarethevariableprojectileoutsideofanyfunction,whichmakesitpublicandexposesittotheUnityeditor.Theprojectileobjectcouldhavebeencreatedincode,howeverifyouwanttomodify(tweak)avariable,it’sbettertodothisfromwithintheUnity第一個參數(shù)projectile是我們想建立的一個對象,那么什么是projectile呢?projectile是一個在你的編輯器內(nèi)的插座,為了允許它產(chǎn)生我們會在任何一個函數(shù)外頭projectile變量。這樣可以使它成為公共的并在Unity編輯器下。Projectile對象能被用代碼產(chǎn)生,不管你是否想編輯或調(diào)整一個變量,最好是在Unity編輯器下。Thesecondparameter,transform.position,createstheprojectileatthesamepositionin3Dspaceasthelauncher.Whythelauncher?Well,thescriptwe’recreatingwillbeattachedtothelaunchersoifwewanttogetourcurrent3Dposition,transform.positiongivesthattous(thetransformkeywordaccessestheTransformoftheGameObjectwherethescriptis第二個參數(shù)transform.position在3D空間中建立projectile的位置,即發(fā)射者的位置,為什么是發(fā)射者?好吧,建立的這個將被附著到發(fā)射者上以便獲得當前我們的3D位置,transform.position將這些返給我們(transform鍵盤存取在里被附著的游戲?qū)ο筇幍腡ransform)Thethirdparameter,transform.rotation,issimilartothesecondparameter,exceptitcreatesthemissilewiththesamerotationpropertiesasthelauncher.第三個參數(shù)是transform.rotation與第二個參數(shù)相似,除了建立一個與發(fā)射者相同的轉(zhuǎn)動屬性的。instantiatedProjectile.velocityinstantiatedProjectile.velocitytransform.TransformDirection(Vector3(0,0,speed)Thenextpartofthecodemakesourmissilemove.Todothis,wegivethemissileavelocity,butinwhichdirection(x,y,orz)?IntheSceneView,clickontheFPSController,themovearrowsappear(press‘W’ifthearrowsdonotappear),oneisred,oneisgreen,andoneisblue.Reddenotesthex-axis,greendenotesthey-axis,andbluedenotesthez-axis.Asblueispointinginthedirectionthatthe yerisfacing,wewanttogiveourmissileavelocityinthez-axis.下面的代碼是的能夠移動。為了做到這一點,給一個速度,但是朝那個方向(x,y,或者z)?在場景視圖中,單擊FPS控制器,移動箭頭顯示(按“W”鍵,如果箭頭不顯示),一個是紅色的,一個是綠色的,并且一個是藍色的,紅色的指示X軸,綠色的指示Y軸,藍色的指示Z軸,藍色的方向是游戲者面對的方向,我們想給我們的在Z軸方向一個速度。Velysarortyfstantatedojctie.Hwdwewhis?instantateProjectlesftypeigib,andfekatteAIweseethatysar.TealkateftherrsthatRyhas,to.Tosethevelocityedtocythednhaxis.Howevr,hreisesligtue.Objectsin3Darespecifiedusingtwocoordinatemodels;localandworld.Inlocalspace,coordinatesarerelativetotheobjectyouareworkingwith.Inworldspace,coordinatesareabsolute:up,forexample,isalwaysthesamedirectionforallobjects.Rigidbody.velocitymustbespecifiedinworldspace.So,whenassigningthevelocityyouneedtoconvertfromthez-axisinlocalspace(theforwarddirection)toitsrespectiveworldspacedirection.Youdothisusingthetransform.TransformDirectionfunctionwhichtakesaVector3asanargument.Thevariablespeedisalsoexposed,sowecantweakitintheeditor.速度是instantiatedProjectile的一個屬性,我們怎么知道的?好吧instantiatedProjectile是一個剛體類型,如果我們查看API就會明白速度是一個屬性,也可以查看剛體的其他一些屬性,為了設置速度我們需要給每一個坐標軸指定速度,然而這時一個微小的議題,在3D在世界空間,坐標軸是,舉例來說,所有物體向上的方向都是指向同一個方向,所以Rigidbody.velocity必須被在世界空間中指定,當你需要在Z軸方向轉(zhuǎn)換一個分配的在本地空間中速度(向前的方向)到它相對于世界空間方向的速度時,你可以使用一個將Vector3作為一個參數(shù)的transform.TransformDirection函數(shù),變量speed也將會被在外,所以我們能在編輯器中調(diào)整它。Physics.IgnoreCollision(Physics.IgnoreCollision(instantiatedProjectile.collider,transform.root.collider);}}Finally,weturnoffcollisionsbetweenthemissileandtheyer.Ifwedidn’tdothisthemissilewouldcollidewiththeyerwhenitwasinstantiated.LookthisupintheAPIunderIgnoreCollision.Hereisthefullcodeto這里是MissileLauncher.js的全部varvarprojectile:Rigidbody;varspeed=20;function{if(Input.GetButtonDown("Fire1"){varinstantiatedProjectile:Rigidbody=Instantiate(projectile,transform.position,transform.rotation);instantiatedProjectile.velocity=transform.TransformDirection(Vector3(0,0,speed));Physics.IgnoreCollision(instantiatedProjectile.collider,transform.root.collider);}}InsertthedescribedcodeintoMissileLauncherJavascriptandsave插入這些被說明的代碼到MissileLauncherJavascript中并且保存它。AttachtheMissileLauncherscripttotheLauncherintheFPSController.YoucanconfirmthattheMissileLauncherscriptisnowattachedtotheLauncherbyLauncheritintheHierarchyViewandcheckingthattheMissileLauncherscriptisshowntheInspector被附著到發(fā)射者上了,選擇在層次視窗中的發(fā)射者,在檢查面板中能看到MissileLauncher本Themissileprefabwepreviouslycreatedhasnotbeenassociatedwiththeprojectilevariableinourscript,sowemustdothisinsidetheeditor.TheprojectilevariableisoftypeRigidbody,sofirstwemustensurethatourmissilehasaRigidbodyattached.在我們的中我們先前創(chuàng)建的預制物體還沒有被分配到變量projectile上,所以須編輯器下做這個,projectle變量是剛體類型,所以首先須確保我們的有一個附著的剛體組件ClickontheMissileintheProjectpanel,thenfromthemain barselecttofire.Wehavetodothisasthetypeofobjectwewanttofiremustmatchthetypeofthevariableweexposedinthescript.單擊項目面板Missile,然后再主菜單下選擇Components>Physics>Rigidbody,將會增加一個剛體組件到我們用來開火的Missile對象上,我們想拿來開火的我們做的這個對象類Associatethemissilewiththeprojectilevariableinthescript.First,clickonLauncherintheHierarchypanel,noticethevariableProjectileintheMissileLauncherscriptsectionintheInspectorpanel.NowdragtheMissileprefabfromtheProjectpanelanddropitontotheProjectilevariable.上的MissileLauncher中的Projectile變量,現(xiàn)在從項目面板上拖拽Missile預制物體到Nowifyourunthegameyouwillbeabletoshootoutasmallspherewhichwillbeaffectedbygravity.現(xiàn)在你能運行游戲,你將能射出一個小的有重力效果的MissileexplosionsNowwe’regoingtoaddanexplosionwhenthemissilecollideswithanotherobject.Todothisweneedtoattachbehaviortothemissile,i.e.,createanewscriptandaddittotheMissilegameobject.現(xiàn)在增加一個,當跟另一個物體發(fā)生碰撞的時候,做這些我們需要給增加CreateanewblankscriptbyselectingAssets>Create>JavascriptandrenamethisnewscripttoProjectile.DragthenewscripttotheWeaponScriptsfolderintheProject建立一個新的空白,選擇Assets>Create>Javascript并且重命名這個新的Projectile,拖拽這個新的到項目面板上的 SowhatdowewanttheProjectiletodo?Wewanttodetectwhenthemissilehashadacollisionandcreateanexplosionatthatpoint.Let’slookatthecode:那么我們想讓Projectile怎么做呢?當發(fā)生了一個碰撞時我們想檢測到它并且在那個點上建立一個效果讓我們看一下這個代碼:varvarexplosion:functionOnCollisionEnter(collision:Collision{AnycodethatweputinsidetheOnCollisionEnterfunctionisexecutedwhenevertheobjectthatthescriptisattachedisincollisionwithanotherobject.當附著的對象與另一個對象發(fā)生碰撞時我們寫到OnCollisionEnter函數(shù)中的任何代碼都會被執(zhí)行varvarcontact:ContactPoint=ThemaintakwewnttooieheOnCollsoEnternstonstntiateanwnathenn3Dcevrthemssilecollided.,redthecoha?ThenOnCollsorsasdaCollisincsshconainshisrmatio.ThetatichthecolncurrdsstredntheCntactPointvaria這里的主要任務是在發(fā)生碰撞的3D空間中我們想在OnCollisionEnter函數(shù)內(nèi)初始化一個新的效果。那么碰撞在哪里發(fā)生?OnCollisionEnter函數(shù)是通過一個包含了這些信息的Collision類得到的碰撞在哪里發(fā)生的,碰撞發(fā)生的地點在ContactPoint變量中。varrotation=Quaternion.FromToRotation(Vector3.up,contact.normal);varinstantiatedExplosion:GameObject=Instantiate(explosion,contact.point,rotationHereweusetheInstantiatefunctiontocreateanexplosion.Weknowthatinstantiatetakes3parameters;(1)theobjecttoinstantiate,(2)the3Dposition,and(3)therotationoftheobject.這里我們使用Instantiate函數(shù)建立一個,我們知道Instantiate帶了三個參數(shù),(1)對象實例;2)3D位置;3)對象的旋轉(zhuǎn)角度;Wewillassignthistoagameobjectwithaparticlesystemlater.We’llalsowanttoassignthisusingtheeditor,sowe’llexposethisvariablebymakingitpublic(declaringitoutsideofanyfunction).我們以后將分配一個例子系統(tǒng)到這個游戲?qū)ο笊?,我們也想使用編輯器來分配,所以使Thesecondparameter,the3DpointatwhichtoInstantiatetheexplosionwasdeterminedfromthecollisionclassinpoint2.第二個參數(shù),在用來初始化話效果的3D點,是被碰撞類的第2點來決定的Thethirdparameter,therotationtosettheexplosionto,needssomeex nation.Wewanttherotationoftheexplosionsothatthey-axisoftheexplosionfollowsalongthesurfacenormalofthesurfacethemissilecollidedwith.Thismeansthatforwallstheexplosionshouldfaceoutwards,forfloorsitwillfaceupwards.Sowhatwewanttodoistranslatethey-axisoftheexplosioninlocalspace(they-axisisupwards),tothesurfacenormal(inworldspace)oftheobjectthatwascollidedwith.Essentiallytherotationissaying‘makethey-axisoftheobjectpointinthesamedirectionasthenormalofthesurfacewithwhichitcollided’.第三個參數(shù),設置的旋轉(zhuǎn)角度,需要一些說明,我們想旋轉(zhuǎn)的角度以便的Y軸沿著正常的碰撞的表面,這意味著要面對墻壁向外,它的底層向上,所在被碰撞對象的正常表面上我們這些在本地空間被轉(zhuǎn)換到了Y軸上(Y軸是向上的)。質(zhì)上旋轉(zhuǎn)是說“使對象點的Y軸與它碰撞的正常表面同一個方Destroy(Destroy(gameObject}Finally,wewanttomakethemissiledisappearfromthegameasithasnowcollided,whichisdonebycallingtheDestroy()functionwithgameObjectasaparameter(gameObjectdenotestheobjectthescriptisassociatedwith).Hereisthefullcodeto最后,在游戲里我們想使在它發(fā)生碰撞的地方,在此處調(diào)用帶一個gameObject參數(shù)varvarexplosion:functionOnCollisionEnter(collision:Collision{varcontact:ContactPoint=varrotation=Quaternion.FromToRotation(Vector3.up,contact.normal);varinstantiatedExplosion:GameObject=Instantiate(explosion,contact.point,rotation);Destroy(gameObject);}AddthecodeintotheProjectileJavascriptandsave增加這些代碼到ProjectileJavascript中并保存它AttachtheProjectileJavascripttotheMissileprefabbyComponent>Scripts通過選擇Component>Scripts>Projectile附著ProjectileJavascript到Missile預制物Nowwehavetocreatetheexplosionthatwewanttooccurwheneverthemissile現(xiàn)在我們建立一個效果,在發(fā)生碰撞時使用First,createanewPrefab(callitExplosion)thatwillstoretheexplosion首先,建立一個新的預制物體(調(diào)用它會產(chǎn)生),它到asset資源中ThestandardassetscontainaniceexplosionprefabwithaparticlesystemandalightintotheHierarchyView.標準的資源中包含一個好的帶一個例子效果和周圍有燈光的預制體,在層次視窗StandardAssets/Particles/explosion拖拽預制物Adjustthesettingsontheexplosionuntilyou’rehappywithhowitlooks,thendragtheExplosionfromtheHierarchyviewontotheExplosionPrefabintheProjectpanel.調(diào)整設置直到你希望看到的效果,這時從層次視窗中拖拽到項目面板上的預制物Nowwecanassigntheexplosiontothe現(xiàn)在我們能分配預制物到上EnsuringthatMissileprefabisselected,fillintheExplosionvariablebydraggingtheExplosionobjectintheProjectpanelontotheMissile’sExplosionvariableintheInspector確保投射預制物體被選擇,在項目面板上通過拖拽填充Explosion對象到層次面板ExplosionDefiningExplosionBehavior定義行Nowwehavetocreateonemorescriptwhichwilldefinethebehavioroftheexplosion現(xiàn)在我們定義的來定義自身的行為Createanewscript,callitExplosion,andputitintheWeaponsfolder.DoubleclickontheExplosionscripttoeditit.建立一個新的,讓Explosion調(diào)用它,并且將它放到 下,在Explosion雙擊進行編輯AnothercommonfunctiontypeforscriptsiscalledStart().Code cedinsidehereisexecutedonlyoncewhentheobjectitbelongstoisinstantiated.Allwewanttodofornowistodeletetheexplosionfromthegameafteracertainamountoftime.TodothisweusetheDestroy()functionwithasecondparameterwhichspecifieshowlongtowaitbefore僅被執(zhí)行一次,所有的我們現(xiàn)在就是當正確的時間計數(shù)完了以后從游戲中刪除,為varvarexplosionTime=1.0;functionStart(){Destroy(gameObject,explosionTime}TheexplosionTimevariableisexposedtotheUnityeditorsoitcanbeeasilyexplosionTime變量被在Unity編輯器重以便我們能容易地調(diào)整InserttheabovecodeintotheExplosionscript,deletingtheUpdate()functioninthe插入上面的代碼到Explosion中,在進程中刪除Update()函數(shù)AttachtheExplosionscripttotheExplosionprefabbyfirstclickingontheExplosionprefabandthenselectingComponents>Scripts>Explosion.在Explosion預制物體上首先單擊,將Explosion附著到Explosion預制物體上然后選Components>ScriptsNoticehowwe’vetriedtogroupthebehaviorasneatlyaspossibly,codethatrelatestotheexplosioniscontainedwithinthescriptthatisattachedtotheExplosionprefab.注意如果可能的話我們嘗試歸整行為,被包含在中關聯(lián)到的代碼被附著在Explosion預制物體上Runthegameandwhereveryourmissilecollideswiththeenvironment,youshouldseetheexplosionparticlesystemforaperiodoftime.運行游戲并且無論你在環(huán)境中怎么,你都能在期望的時間看到的粒子效Soundeffects聲音效Ourgameworldhasbeenalittlequietsofar,let’saddasoundeffecttoourexplosion到目前為止我們的游戲世界有一點安靜,讓我們增加一個聲音效果給我們的效Firstlet’sassignanaudiocliptotheExplosion首先讓我們分配一個聲音片段到Explosion預制物ToallowtheExplosionobjecttobeabletoacceptanaudioclip,weaddtheAudioSourcecomponenttoitfromthemain (Component>Audio>AudioSource).You’llnoticeoneofthepropertiesofthiscomponentistheAudioClip.為了允許Explosion對象能夠接受一個聲音片段,我們從主菜單增加聲音源組件到它身(Component>Audio>AudioSource)。你將注意到組件里有一個屬性是AudioClipAssign" LauncherImpact"totheExplosionprefab’sAudioClipexposedvariable.Unitycan ymanydifferentaudioformats.分配“LauncherImpact”給Explosion預制物體的AudioClip這個的變量,Unity許多不同格式Runthegameagainandourexplosionsoundeffectshouldbeheardwheneachmissileimpact.再一次運行游戲在每次碰撞時都能聽AddingaGUI增加一個Nowlet’saddagraphicaluserinterface(GUI),morecommonlyknownasaheadsup y(HUD)tothegame.OursimpleGUIisonlygoingtocontainacrosshair.Addinga 增加一個十字形瞄準CreateadirectorycalledGUIinyourproject在你的項目視窗中建立一個叫做GUICreateanewscript,callitCrosshairanddragittotheGUI建立一個新的,十字形瞄準線將調(diào)用它并將這個拖拽到 Enterthefollowingcodeinto鍵入隨后的代碼到Crosshair.js中varvarcrosshairTexture:Texture2D;varposition:Rect;function{position=Rect((Screen.width-crosshairTexture.width)/2,(Screen.height-crosshairTexture.height)/2,crosshairTexture.width,crosshairTexture.height}function{GUI.DrawTexture(position,crosshairTexture}Firstwecreatetwovariables.Thefirstvariableiswherewe’regoingtoputtheimagethatwe’regoingtouseforourtexture.Thesecondvariableistherectanglewhichwillstorewheretopositionthetextureonthescreen.InsideoftheStart()functionwecalculatewherethetexturewillbedrawn.Insideoftheconstructorwehave4parameterswhichdeterminewheretherectangleislocatedandhowlargeitis.Thefirstparameter lsuswheretheleftsideoftherectangleis.Thesecondparametersetsthebottomoftherectangle.Thethirdand parametersdeterminethewidthandheightoftherectangle.InsideOnGUI()weusethefunctionalityoftheGUIclasstodrawitemsonscreen.InthiscasewecallDrawTexture()andpassitthepositionandcrosshairTexture.Thisfunctionwillthendrawourcrosshairinthecenterofthescreen.在OnGUI()函數(shù)中我們使用GUI類的功能將項目畫在屏幕上,在這種情況下我們調(diào)DrawTexture()并且傳遞它的位置和十字形瞄準線材Savethe保CreateanewemptygameobjectandrenameitDragyourCrosshairscriptontotheGUIgameobject.SelecttheGUIgameobjectandthendragtheaimtexturefoundatfromtheProjectviewtotheCrosshairTexturevariableinthe yandthereshouldbeacrosshairinthecenterofthegame按下運行按鈕在游戲屏幕的中心會出現(xiàn)十字瞄準Physics物Nowwewantobjectsinourenvironmenttobehaveasnaturallyaspossible,thisisachievedbyaddingphysics.Inthissectionwe’regoingtoaddobjectstotheenvironmentwhichwillmovewhenhitwithourmissile.Firsttherearesomenewtermstoex 節(jié)增加對象到環(huán)境中,可以用我們的打擊它。首先有一些新的術語要解釋。Update()更新函Previously,wehaveenteredcodeinsideanUpdatefunction,sothatwecanexecutethatcodeeveryframe.Oneexamplewastodetectiftheuserhadhitthefirebutton.However,framerateisnotaregularvalueasitisdependentonthecomplexityofthesceneetc.Thisirregulartimingbetweenframescanleadtounstablephysics.Therefore,wheneveryouwanttoupdateobjectsinyourgamewhichinvolvephysics(rigidbodies),codeshouldbecedinsideaFixedUpdatefunction.ThedeltaTimevalueinUnityisusedtodeterminethetimetakenbetweenrenderingtwoconsecutiveframes.AgeneraldistinctionbetweenUpdateandFixedUpdatefunctionsisasfollows:以前我們在Update函數(shù)中鍵入代碼,以便我們能在畫面的每一幀都執(zhí)行它,一個例子是我們檢測用戶是否單擊了開火按鈕,然而,幀的速率是不規(guī)則的值,它依賴場景等的復雜程度,這個介于多幀之間的不規(guī)則變化的時間可能導致不穩(wěn)定的物理特性,因此,無論何時你想更新你的需要物理特性(剛體)的游戲中的對象時,代碼一定要寫到FixedUpate函數(shù)中,在Unity中的deltaTime的值被用來決定渲染兩個連續(xù)幀之間所花的時間。在Update和FixedUpdate函數(shù)之間的一個普通的區(qū)別像隨后的一樣:Update()–codeinsidethefunctiontypically yerbehavior,gamelogic,etc.valueofdeltaTimeisnotconsistentwhenusedwithinthis在函數(shù)內(nèi)鍵入更新游戲者的行為、游戲邏輯等的代碼,當在函數(shù)中使用ate()時deltaTime的值是不一致的。FixedUpdate()–codeinsidethisfunctiontypicallyupdatesrigidbodiesovertime(physicsbehavior).ThedeltaTimealwaysreturnsthesamevaluewhencalledwithinaFixedUpdate在函數(shù)內(nèi)鍵入剛體隨時間的變化(物理行為)。當調(diào)用一個FixedUpdatedeltaTime總ThefrequencywithwhichFixedUpdateiscalledisspecifiedbytheFixedTimesteppropertyin optionEdit>ProjectSettings>Timeandcanalsobealtered.Thispropertycontainsthetimeinsecondstogettheframespersecondvalueandtakethereciprocalofthisvalue.FixedUpdate被調(diào)用的頻率是由在菜單選項Edit>ProjectSettings>Time中的固定時間間隔值并且采用了它的倒數(shù)(F=1/T即物理:頻率=1/周期) WhenmodifyingthevalueforFixedTimestep(effectivelyframespersecond),carefultostrikeabalance;asmallertimestepwillgivemorestablephysics(moreaccuracy),howeverthegameperformancewillsuffer.Ensurethatthegamerunsquicklyandthephysicsseemrealistic.當編輯固定時間間隔(FixedTimestep等效于每幀之間的時間)時要取得平衡;一個小的Thefinaltermtoex ininthissectionisyield.Thiscanbethoughtofasastatementtopauseexecutionofthecurrentfunction.在本節(jié)最后解釋的術語是yield。這可以看作是一個暫停執(zhí)行當前函數(shù)的Solet’sgetbacktoourgame,whatdowewantto所以讓我們返回我們的游戲,看我們到底想做什Allowtheusertofireamissile(already允許用戶發(fā)射(已經(jīng)做了Ifthemissilecollideswithanotherrigidbody,determineifthereareanyotherobjectsinthevicinitywhichhaverigidbodiesattached.Foreachrigidbodywithinthe oftheexplosion,givethema intheupwardsdirection,causingthemtoreacttothemissile.每個剛體內(nèi)都有效果影響,給他們一個向上的力,以使它們對做出反應Let’slookatthecodefortheupdatedExplosionvarexplosionTime=1.0;varvarexplosionTime=1.0;varexplosionRadius=5.0;varexplosionPower=function讓我們看這段更新了的Explosion讓我們看這段更新了的Explosion{//Destroytheexplosioninx//在X秒后銷 //thiswillgivetheparticlesystemandaudioenoughtimeto //將給出足夠的時間完成運行粒子系統(tǒng) 聲Destroy(gameObject,explosionTime//Findallnearbyvarcolliders:Collider[]=Physics.OverlapSphere(transform.position,explosionRadius);Firstwedetermineifthereareanyobjectswithcollidersclosetowherethemissilelanded.TheclassfunctionPhysics.OverlapSphere()takestwoparameters:a3Dpositionandradiusandreturnsanarrayofcolliderswhicharecontainedwithinthedefinedsphere.首先我們確定如果這里有其它任何帶有碰撞器的對象在降落地方的附近。這個類函數(shù)Physics.OverlapSphere()帶了兩個參數(shù):一個3D位置和半徑并且返回碰撞器數(shù)組,被包含在已定義的sphere球體內(nèi)//Apply//Applytoallsurroundingrigidfor(varhitincollide
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 節(jié)日主題教育活動計劃
- 二零二五年度林業(yè)樹木清理與可持續(xù)利用合同3篇
- 2025版隧洞施工合同:隧道施工合同履約保證與履約擔保協(xié)議3篇
- 二零二五年度鋼材料國際采購合同標準范本
- 二零二五年度個人購房裝修分期付款合同樣本3篇
- 二零二五年度樓房居間買賣合同(含家具家電)4篇
- 二零二五年度個人對網(wǎng)絡安全企業(yè)借款合同4篇
- 防水套管后補做法施工方案
- 二零二五年度鋼廠廢鋼回收處理及環(huán)保設施建設合同
- 二零二五年度企業(yè)品牌形象托管授權合同3篇
- 軍人結婚函調(diào)報告表
- 民用無人駕駛航空器實名制登記管理規(guī)定
- 繪本分享《狐貍打獵人》
- 北京地鐵6號線
- 航空油料計量統(tǒng)計員(初級)理論考試復習題庫大全-上(單選題匯總)
- (39)-總論第四節(jié)針灸處方
- 《民航服務溝通技巧》教案第10課兒童旅客服務溝通
- 諒解書(標準樣本)
- 西班牙語構詞.前后綴
- 《工程測試技術》全套教學課件
評論
0/150
提交評論