黑馬五期fps游戲教程_第1頁(yè)
黑馬五期fps游戲教程_第2頁(yè)
黑馬五期fps游戲教程_第3頁(yè)
黑馬五期fps游戲教程_第4頁(yè)
黑馬五期fps游戲教程_第5頁(yè)
已閱讀5頁(yè),還剩16頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

FPS游戲Part1Introduction第一部ThistutorialwilldetailhowtomakeasimpleFirst Shooter(FPS).Itwillintroducefundamental3DgameprogrammingconceptsandgivetipsonhowtothinklikeagameSettingupthegameenvironment安裝游戲Oncetheassetshavebeenimported,you’llnoticetherearemanyfoldersintheProject一旦資源被導(dǎo)入,你將注意到項(xiàng)目面板上有許在項(xiàng)目面板上,從Objects/mainLevelMesh/mainLevelMesh中選擇IntheInspectorpanel,insideoftheFBXImporteroptionsyou’llfindthe"GenerateColliders"option.Togglethatoptionon.Ifwedon’tdothis,the yerwillsimplyfallthroughthelevel(noDragthemainLevelMeshintothe拖拽mainLevelMesh到場(chǎng)Thereisnoneedtoaddalighttothescene,thelevelisalreadyfullylightmapped.Theimportedleveluseslightmapsforalllightingwhichallowsustouseprebakedshadows.使用prebakedShadows預(yù)焙陰影。Lightmapsareverygoodforperformance,especiallyifyouwanttocreateacomplexlightingsetup.光影執(zhí)行起來(lái)非常好,尤其是你想建立一個(gè)復(fù)雜的燈光設(shè)置的You’renowreadytoaddacharacterintothe你現(xiàn)在準(zhǔn)備要給環(huán)境中增加一個(gè)特AddingtheMainCharacter增加主要的特We’renowgoingtoaddinacharacterfor yertocontrol.Unityhasabuiltprefabspecificallyforafirst controller.ThiscanbefoundintheProjectpanelunderStandardAssets>Prefabs.人稱控制器,它能在項(xiàng)目面板的StandardAssets>Prefabs下面ToaddtheFirst Controller,clickonthearrowbesideStandardAssetsintheProjectpanel,aslistofassetswillappear.FindthefoldercalledPrefabsandclickonthearrowinthelefthandside.YoushouldnowseetheFirst controllerasset.DragthisintotheSceneview.為了增加第一人稱控制器,單擊項(xiàng)目面板上的StandardAssets,所有的資源將被列出,發(fā)現(xiàn)Youshouldseeacylinderobjectrepresenting yer,3largearrowsforthelocationin3Dspacefortheobject(ifyoudonotsee3arrowspressthe‘W’key),andawhitemeshwhichshowstheobject’sviewport(whereitiscurrentlylooking).TheFPSControllerisnowthedefaultcamera,bymovingthisobject,youchangethecurrentviewintheGameView.You’llalsonoticethattheFPSControllerhasacameraiconontopofit.Movethecharactersothatitisabovegroundlevelintheenvironment.用來(lái)在環(huán)境繞場(chǎng)地的。AswenolongerhaveanyneedfortheMainCamera,youcandelete因?yàn)橹髡障鄼C(jī)我們不再需要它了,所以你可以刪 y,youshouldnowbeabletomovearoundthelevelbyusingthemouseandkeyboard(cursorkeystomoveorW,A,S,D).按下“y”,你可以使用鼠標(biāo)和鍵盤(pán)圍繞場(chǎng)地移動(dòng)(鼠標(biāo)鍵移動(dòng)和按“W”、“A”、“S”You’venowcreatedaverysimpleFPS,let’sgive yera你現(xiàn)在建立了一個(gè)非常簡(jiǎ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建立一個(gè)發(fā)射First,let’saddinagameobjecttorepresentthegrenadelauncher.Agameobjectisanyiteminthe3Dworld( yer,level,sounds),componentsarethepropertiesthatthegameobjecthas.Thereforeyouapplycomponentstogameobjects.首先,讓我們?cè)黾右粋€(gè)游戲?qū)ο笠员硎景l(fā)射者。一個(gè)游戲?qū)ο笫?D世界中的任何一個(gè)事項(xiàng)(游戲者、層面、聲音)Fromthemain selectGameObject>CreateEmpty,andrenametheobjectto"Launcher"intheHierarchypanel.Note,thisobjectisinvisibleasitisandemptyhoweveritisjust ceholderforourmissile從主菜單上選擇GameObject>CreateEmpty,并且在層次面板上重命名對(duì)象為Nowlet’sgetinclosetoourFPScontrollersowecanseewheretopositiontheweaponlauncher.現(xiàn)在讓我們關(guān)閉FPS控制器以便我們能看到發(fā)射者的位SelecttheFPScontrollerintheHierarchyPanelandensuringthatyourcursorisovertheSceneView,press‘F’(frameselected).Thisfocusesusonthe yer(thecurrentlyselecteditem).NowselecttheLauncherfromtheHierarchyPanelandchooseGameObject>Movetoviewfromthemain .NoticehowtheLauncherobjectisnow cedneartheFPSController.Wecannowusethehandlesto cethelauncherapproxima ywherethehandsshouldbe.現(xiàn)在在層次面板上選擇發(fā)射者并且選擇GameObject>Movetoviewfromthemain ,意發(fā)射者對(duì)象是怎么被定為到靠近FPS控制器的。我們現(xiàn)在能使用手柄大概定位發(fā)射者到手柄使用的地方。NOTEYoucanmakethecharacterleftorright-handedbyalteringthelocationofthisobject,noneedtochangeanycode.意你可以通過(guò)改變這個(gè)對(duì)象的向左或向右的特性以改變對(duì)象的定位而沒(méi)有必要改變?nèi)蜯akesureyourUnitywindowlayoutisin2by3mode(Window>Layouts>2by3),andpressthe ybutton.MakesureLauncherisselectedintheHierarchyViewandwhilstwatchingtheSceneView,movethecharacteraround.You’llnoticethatourlauncherobjectdoesnotmovewithourcharacter(youcanpress ytostopthegamerunningnow).確保你的Unity窗口布局是2by3模式(WindowLayouts2by3),并且按下運(yùn)行按鈕。確保TosolvethisproblemdragtheLauncherobjectontotheMainCameraobjectthatbelongstotheFPSControllerintheHierarchypanel.ItisokaytobreakthePrefabconnection.NowrunthegameagainandwatchtheSceneView,theLaunchershouldnowmovewithourcharacter.WehaveassociatedtheLaunchergameobjectwithanobjectthatmovesinall3axes(thecamera).CreatetheMissileobject建立一 對(duì)Let’screatethemissilethatwillbelaunchedwhentheuserclicksthefireFornowwe’llusesomethingsimple,asphere.CreateanewprefabobjectbyclickingAssets>Create>Prefabfromthe bar,andrenameitto眼下使用一些簡(jiǎn)單物體,一個(gè)球(sphere),建立一個(gè)預(yù)制物體對(duì)象在Unity菜單條上單擊AssetsCreate>Prefab,并且重命名它為MissileNowcreateasphere(GameObject>CreateOther現(xiàn)在建立一個(gè)球(GameObject>CreateOtherNowdragtheSpheregameobjectfromtheHierarchyPanelontotheMissileprefabintheProjectPanel.Theiconfortheprefabwillnowchange.YoucandeletetheSphereobjectfromtheHierarchyView.現(xiàn)在從層次面板上拖拽球游戲?qū)ο蟮巾?xiàng)目面板上的missile預(yù)制物體(prefab)中,預(yù)制物體的圖標(biāo)將被改變。你可以從層次面板上刪除球?qū)ο蟆?Anygameobjectwhichyouknowyou’llneedtoinstantiateatruntimeShouldbeaWritetheMissileLaunchercode寫(xiě)發(fā)射者代TheFPSControllerisaprefabconsistingofseveralgameobjectandcomponents.TheFPSControlleritselfisacylindricalmeshthatonlyrotatesaroundthey-axis,soifweattachthelaunchercode(script)tothis,thenwewon’tbeabletoshootupanddown.Therefore,we’regoingtoattachourlaunchercodetotheMainCamerainsidetheFPSControllerasthecameracanlookinanydirection.擊,因此我們的發(fā)射者代碼附著到了FPS控制器內(nèi)的主照相機(jī)上,作為照相機(jī)可以看任Let’screateourfirstJavascriptcodewhichwilldescribethebehaviourofthe讓我們建立我們的第一個(gè)用來(lái)描述發(fā)射者行為的Javascript代SelectAssets>Create>JavaScript,whichcreatesablankJavascript .AnewassetappearsintheProjectPanelentitledNewBehaviourScript.Renamethisscriptto選擇AssetsCreate>JavaScript,用來(lái)建立一個(gè)空白的Javascript文檔,一個(gè)新的名為能指定你想在Unity中使用的擴(kuò)展的代碼編輯器,通過(guò)單擊Unity>Preferences然后選擇theExternalScriptEditorboxCreateanewdirectoryinsideyourProjectViewcalledWeaponScripts,we’llputallourweaponsscriptsinhere.MoveyourMissileLauncherjavascriptintohere,andmovetheMissileprefabalso. 這,的MissileLauncherjavascript遷移到這里,并且預(yù)制物體也這樣移動(dòng)。Let’shavealookatthecompleteJavascriptforMissileLauncher.Youcantypeinthecodesectionsasyoufollow.ThinkingfromahighlevelwhatdowewanttodoWell,wewanttodetectwhentheuserhashitthefirebutton,theninstantiateanewmissile,andlaunchitwithacertainvelocitytowardswheretheuserwasaiming.Let’sexaminethecodeindetail:varvarprojectile:Rigidbody;varspeed=20;function{Thisisthebeginningofthescript,whichdefinestopropertiesanddeclaresafunctioncalledUpdate.這是的開(kāi)始部分,在這里定義了一些屬性和一個(gè)叫Update的函if(Input.GetButtonDown("Fire1")Firstwewanttocheckwhentheuserhitsthefirebutton."Fire1"ismappedtoboththeleftmousebuttonandthecurrentkeyboardconfiguration(thiscanbeeditedfromEditor>ProjectSettings配置上(這可以通過(guò)菜單Editor>ProjectSettings>Input編輯){{varinstantiatedProjectile:Rigidbody=Instantiate(projectile,transform.position,transform.rotation);Wedeclareavariabletoholdareferencetotheinstantiatedobject.ThetypeofthisvariableisRigidbody,thisisbecausethemissileshouldhavephysicsbehavior.我們?yōu)榱顺跏蓟瘜?duì)象一個(gè)控制參照變量,這個(gè)類型是Rigidbody(剛體類型),這時(shí)因?yàn)檫@個(gè)有一些物理特性和行為。ToinstantiateanobjectinUnityweusetheInstantiatefunctionwiththreeparameters,theobjecttoinstantiate,the3Dpositionitshouldbecreatedat,andtherotationtheobjectshouldhave.Thereisalsoanotherconstructor,checktheAPIguide,butwe’llusethisonefornow.在Unity中初始化一個(gè)對(duì)象我們使用帶三個(gè)參數(shù)的Instantiate函數(shù),這個(gè)對(duì)象被初始化后,用這個(gè)函數(shù)初始化它的3D位置,并且轉(zhuǎn)動(dòng)這個(gè)對(duì)象。這里也有另外一個(gè)構(gòu)造器,參考檢查API指南,但我們現(xiàn)在將用這個(gè)。Thefirstparameter,projectile,istheobjectwewanttocreate.Sowhatisprojectileanyway?Theprojectileissetbyyouinsidetheeditor.Toallowthistohappen,wedeclarethevariableprojectileoutsideofanyfunction,whichmakesitpublicandexposesittotheUnityeditor.Theprojectileobjectcouldhavebeencreatedincode,howeverifyouwanttomodify(tweak)avariable,it’sbettertodothisfromwithintheUnity第一個(gè)參數(shù)projectile是我們想建立的一個(gè)對(duì)象,那么什么是projectile呢?projectile是一個(gè)在你的編輯器內(nèi)的插座,為了允許它產(chǎn)生我們會(huì)在任何一個(gè)函數(shù)外頭projectile變量。這樣可以使它成為公共的并在Unity編輯器下。Projectile對(duì)象能被用代碼產(chǎn)生,不管你是否想編輯或調(diào)整一個(gè)變量,最好是在Unity編輯器下。Thesecondparameter,transform.position,createstheprojectileatthesamepositionin3Dspaceasthelauncher.Whythelauncher?Well,thescriptwe’recreatingwillbeattachedtothelaunchersoifwewanttogetourcurrent3Dposition,transform.positiongivesthattous(thetransformkeywordaccessestheTransformoftheGameObjectwherethescriptis第二個(gè)參數(shù)transform.position在3D空間中建立projectile的位置,即發(fā)射者的位置,為什么是發(fā)射者?好吧,建立的這個(gè)將被附著到發(fā)射者上以便獲得當(dāng)前我們的3D位置,transform.position將這些返給我們(transform鍵盤(pán)存取在里被附著的游戲?qū)ο筇幍腡ransform)Thethirdparameter,transform.rotation,issimilartothesecondparameter,exceptitcreatesthemissilewiththesamerotationpropertiesasthelauncher.第三個(gè)參數(shù)是transform.rotation與第二個(gè)參數(shù)相似,除了建立一個(gè)與發(fā)射者相同的轉(zhuǎn)動(dòng)屬性的。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.下面的代碼是的能夠移動(dòng)。為了做到這一點(diǎn),給一個(gè)速度,但是朝那個(gè)方向(x,y,或者z)?在場(chǎng)景視圖中,單擊FPS控制器,移動(dòng)箭頭顯示(按“W”鍵,如果箭頭不顯示),一個(gè)是紅色的,一個(gè)是綠色的,并且一個(gè)是藍(lán)色的,紅色的指示X軸,綠色的指示Y軸,藍(lán)色的指示Z軸,藍(lán)色的方向是游戲者面對(duì)的方向,我們想給我們的在Z軸方向一個(gè)速度。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的一個(gè)屬性,我們?cè)趺粗赖模亢冒蒳nstantiatedProjectile是一個(gè)剛體類型,如果我們查看API就會(huì)明白速度是一個(gè)屬性,也可以查看剛體的其他一些屬性,為了設(shè)置速度我們需要給每一個(gè)坐標(biāo)軸指定速度,然而這時(shí)一個(gè)微小的議題,在3D在世界空間,坐標(biāo)軸是,舉例來(lái)說(shuō),所有物體向上的方向都是指向同一個(gè)方向,所以Rigidbody.velocity必須被在世界空間中指定,當(dāng)你需要在Z軸方向轉(zhuǎn)換一個(gè)分配的在本地空間中速度(向前的方向)到它相對(duì)于世界空間方向的速度時(shí),你可以使用一個(gè)將Vector3作為一個(gè)參數(shù)的transform.TransformDirection函數(shù),變量speed也將會(huì)被在外,所以我們能在編輯器中調(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插入這些被說(shuō)明的代碼到MissileLauncherJavascript中并且保存它。AttachtheMissileLauncherscripttotheLauncherintheFPSController.YoucanconfirmthattheMissileLauncherscriptisnowattachedtotheLauncherbyLauncheritintheHierarchyViewandcheckingthattheMissileLauncherscriptisshowntheInspector被附著到發(fā)射者上了,選擇在層次視窗中的發(fā)射者,在檢查面板中能看到MissileLauncher本Themissileprefabwepreviouslycreatedhasnotbeenassociatedwiththeprojectilevariableinourscript,sowemustdothisinsidetheeditor.TheprojectilevariableisoftypeRigidbody,sofirstwemustensurethatourmissilehasaRigidbodyattached.在我們的中我們先前創(chuàng)建的預(yù)制物體還沒(méi)有被分配到變量projectile上,所以須編輯器下做這個(gè),projectle變量是剛體類型,所以首先須確保我們的有一個(gè)附著的剛體組件ClickontheMissileintheProjectpanel,thenfromthemain barselecttofire.Wehavetodothisasthetypeofobjectwewanttofiremustmatchthetypeofthevariableweexposedinthescript.單擊項(xiàng)目面板Missile,然后再主菜單下選擇Components>Physics>Rigidbody,將會(huì)增加一個(gè)剛體組件到我們用來(lái)開(kāi)火的Missile對(duì)象上,我們想拿來(lái)開(kāi)火的我們做的這個(gè)對(duì)象類Associatethemissilewiththeprojectilevariableinthescript.First,clickonLauncherintheHierarchypanel,noticethevariableProjectileintheMissileLauncherscriptsectionintheInspectorpanel.NowdragtheMissileprefabfromtheProjectpanelanddropitontotheProjectilevariable.上的MissileLauncher中的Projectile變量,現(xiàn)在從項(xiàng)目面板上拖拽Missile預(yù)制物體到Nowifyourunthegameyouwillbeabletoshootoutasmallspherewhichwillbeaffectedbygravity.現(xiàn)在你能運(yùn)行游戲,你將能射出一個(gè)小的有重力效果的MissileexplosionsNowwe’regoingtoaddanexplosionwhenthemissilecollideswithanotherobject.Todothisweneedtoattachbehaviortothemissile,i.e.,createanewscriptandaddittotheMissilegameobject.現(xiàn)在增加一個(gè),當(dāng)跟另一個(gè)物體發(fā)生碰撞的時(shí)候,做這些我們需要給增加CreateanewblankscriptbyselectingAssets>Create>JavascriptandrenamethisnewscripttoProjectile.DragthenewscripttotheWeaponScriptsfolderintheProject建立一個(gè)新的空白,選擇Assets>Create>Javascript并且重命名這個(gè)新的Projectile,拖拽這個(gè)新的到項(xiàng)目面板上的 SowhatdowewanttheProjectiletodo?Wewanttodetectwhenthemissilehashadacollisionandcreateanexplosionatthatpoint.Let’slookatthecode:那么我們想讓Projectile怎么做呢?當(dāng)發(fā)生了一個(gè)碰撞時(shí)我們想檢測(cè)到它并且在那個(gè)點(diǎn)上建立一個(gè)效果讓我們看一下這個(gè)代碼:varvarexplosion:functionOnCollisionEnter(collision:Collision{AnycodethatweputinsidetheOnCollisionEnterfunctionisexecutedwhenevertheobjectthatthescriptisattachedisincollisionwithanotherobject.當(dāng)附著的對(duì)象與另一個(gè)對(duì)象發(fā)生碰撞時(shí)我們寫(xiě)到OnCollisionEnter函數(shù)中的任何代碼都會(huì)被執(zhí)行varvarcontact:ContactPoint=ThemaintakwewnttooieheOnCollsoEnternstonstntiateanwnathenn3Dcevrthemssilecollided.,redthecoha?ThenOnCollsorsasdaCollisincsshconainshisrmatio.ThetatichthecolncurrdsstredntheCntactPointvaria這里的主要任務(wù)是在發(fā)生碰撞的3D空間中我們想在OnCollisionEnter函數(shù)內(nèi)初始化一個(gè)新的效果。那么碰撞在哪里發(fā)生?OnCollisionEnter函數(shù)是通過(guò)一個(gè)包含了這些信息的Collision類得到的碰撞在哪里發(fā)生的,碰撞發(fā)生的地點(diǎn)在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ù)建立一個(gè),我們知道Instantiate帶了三個(gè)參數(shù),(1)對(duì)象實(shí)例;2)3D位置;3)對(duì)象的旋轉(zhuǎn)角度;Wewillassignthistoagameobjectwithaparticlesystemlater.We’llalsowanttoassignthisusingtheeditor,sowe’llexposethisvariablebymakingitpublic(declaringitoutsideofanyfunction).我們以后將分配一個(gè)例子系統(tǒng)到這個(gè)游戲?qū)ο笊?,我們也想使用編輯器?lái)分配,所以使Thesecondparameter,the3DpointatwhichtoInstantiatetheexplosionwasdeterminedfromthecollisionclassinpoint2.第二個(gè)參數(shù),在用來(lái)初始化話效果的3D點(diǎn),是被碰撞類的第2點(diǎn)來(lái)決定的Thethirdparameter,therotationtosettheexplosionto,needssomeex nation.Wewanttherotationoftheexplosionsothatthey-axisoftheexplosionfollowsalongthesurfacenormalofthesurfacethemissilecollidedwith.Thismeansthatforwallstheexplosionshouldfaceoutwards,forfloorsitwillfaceupwards.Sowhatwewanttodoistranslatethey-axisoftheexplosioninlocalspace(they-axisisupwards),tothesurfacenormal(inworldspace)oftheobjectthatwascollidedwith.Essentiallytherotationissaying‘makethey-axisoftheobjectpointinthesamedirectionasthenormalofthesurfacewithwhichitcollided’.第三個(gè)參數(shù),設(shè)置的旋轉(zhuǎn)角度,需要一些說(shuō)明,我們想旋轉(zhuǎn)的角度以便的Y軸沿著正常的碰撞的表面,這意味著要面對(duì)墻壁向外,它的底層向上,所在被碰撞對(duì)象的正常表面上我們這些在本地空間被轉(zhuǎn)換到了Y軸上(Y軸是向上的)。質(zhì)上旋轉(zhuǎn)是說(shuō)“使對(duì)象點(diǎn)的Y軸與它碰撞的正常表面同一個(gè)方Destroy(Destroy(gameObject}Finally,wewanttomakethemissiledisappearfromthegameasithasnowcollided,whichisdonebycallingtheDestroy()functionwithgameObjectasaparameter(gameObjectdenotestheobjectthescriptisassociatedwith).Hereisthefullcodeto最后,在游戲里我們想使在它發(fā)生碰撞的地方,在此處調(diào)用帶一個(gè)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通過(guò)選擇Component>Scripts>Projectile附著ProjectileJavascript到Missile預(yù)制物Nowwehavetocreatetheexplosionthatwewanttooccurwheneverthemissile現(xiàn)在我們建立一個(gè)效果,在發(fā)生碰撞時(shí)使用First,createanewPrefab(callitExplosion)thatwillstoretheexplosion首先,建立一個(gè)新的預(yù)制物體(調(diào)用它會(huì)產(chǎn)生),它到asset資源中ThestandardassetscontainaniceexplosionprefabwithaparticlesystemandalightintotheHierarchyView.標(biāo)準(zhǔn)的資源中包含一個(gè)好的帶一個(gè)例子效果和周?chē)袩艄獾念A(yù)制體,在層次視窗StandardAssets/Particles/explosion拖拽預(yù)制物Adjustthesettingsontheexplosionuntilyou’rehappywithhowitlooks,thendragtheExplosionfromtheHierarchyviewontotheExplosionPrefabintheProjectpanel.調(diào)整設(shè)置直到你希望看到的效果,這時(shí)從層次視窗中拖拽到項(xiàng)目面板上的預(yù)制物Nowwecanassigntheexplosiontothe現(xiàn)在我們能分配預(yù)制物到上EnsuringthatMissileprefabisselected,fillintheExplosionvariablebydraggingtheExplosionobjectintheProjectpanelontotheMissile’sExplosionvariableintheInspector確保投射預(yù)制物體被選擇,在項(xiàng)目面板上通過(guò)拖拽填充Explosion對(duì)象到層次面板ExplosionDefiningExplosionBehavior定義行Nowwehavetocreateonemorescriptwhichwilldefinethebehavioroftheexplosion現(xiàn)在我們定義的來(lái)定義自身的行為Createanewscript,callitExplosion,andputitintheWeaponsfolder.DoubleclickontheExplosionscripttoeditit.建立一個(gè)新的,讓Explosion調(diào)用它,并且將它放到 下,在Explosion雙擊進(jìn)行編輯AnothercommonfunctiontypeforscriptsiscalledStart().Code cedinsidehereisexecutedonlyoncewhentheobjectitbelongstoisinstantiated.Allwewanttodofornowistodeletetheexplosionfromthegameafteracertainamountoftime.TodothisweusetheDestroy()functionwithasecondparameterwhichspecifieshowlongtowaitbefore僅被執(zhí)行一次,所有的我們現(xiàn)在就是當(dāng)正確的時(shí)間計(jì)數(shù)完了以后從游戲中刪除,為varvarexplosionTime=1.0;functionStart(){Destroy(gameObject,explosionTime}TheexplosionTimevariableisexposedtotheUnityeditorsoitcanbeeasilyexplosionTime變量被在Unity編輯器重以便我們能容易地調(diào)整InserttheabovecodeintotheExplosionscript,deletingtheUpdate()functioninthe插入上面的代碼到Explosion中,在進(jìn)程中刪除Update()函數(shù)AttachtheExplosionscripttotheExplosionprefabbyfirstclickingontheExplosionprefabandthenselectingComponents>Scripts>Explosion.在Explosion預(yù)制物體上首先單擊,將Explosion附著到Explosion預(yù)制物體上然后選Components>ScriptsNoticehowwe’vetriedtogroupthebehaviorasneatlyaspossibly,codethatrelatestotheexplosioniscontainedwithinthescriptthatisattachedtotheExplosionprefab.注意如果可能的話我們嘗試歸整行為,被包含在中關(guān)聯(lián)到的代碼被附著在Explosion預(yù)制物體上Runthegameandwhereveryourmissilecollideswiththeenvironment,youshouldseetheexplosionparticlesystemforaperiodoftime.運(yùn)行游戲并且無(wú)論你在環(huán)境中怎么,你都能在期望的時(shí)間看到的粒子效Soundeffects聲音效Ourgameworldhasbeenalittlequietsofar,let’saddasoundeffecttoourexplosion到目前為止我們的游戲世界有一點(diǎn)安靜,讓我們?cè)黾右粋€(gè)聲音效果給我們的效Firstlet’sassignanaudiocliptotheExplosion首先讓我們分配一個(gè)聲音片段到Explosion預(yù)制物ToallowtheExplosionobjecttobeabletoacceptanaudioclip,weaddtheAudioSourcecomponenttoitfromthemain (Component>Audio>AudioSource).You’llnoticeoneofthepropertiesofthiscomponentistheAudioClip.為了允許Explosion對(duì)象能夠接受一個(gè)聲音片段,我們從主菜單增加聲音源組件到它身(Component>Audio>AudioSource)。你將注意到組件里有一個(gè)屬性是AudioClipAssign" LauncherImpact"totheExplosionprefab’sAudioClipexposedvariable.Unitycan ymanydifferentaudioformats.分配“LauncherImpact”給Explosion預(yù)制物體的AudioClip這個(gè)的變量,Unity許多不同格式Runthegameagainandourexplosionsoundeffectshouldbeheardwheneachmissileimpact.再一次運(yùn)行游戲在每次碰撞時(shí)都能聽(tīng)AddingaGUI增加一個(gè)Nowlet’saddagraphicaluserinterface(GUI),morecommonlyknownasaheadsup y(HUD)tothegame.OursimpleGUIisonlygoingtocontainacrosshair.Addinga 增加一個(gè)十字形瞄準(zhǔn)CreateadirectorycalledGUIinyourproject在你的項(xiàng)目視窗中建立一個(gè)叫做GUICreateanewscript,callitCrosshairanddragittotheGUI建立一個(gè)新的,十字形瞄準(zhǔn)線將調(diào)用它并將這個(gè)拖拽到 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類的功能將項(xiàng)目畫(huà)在屏幕上,在這種情況下我們調(diào)DrawTexture()并且傳遞它的位置和十字形瞄準(zhǔn)線材Savethe保CreateanewemptygameobjectandrenameitDragyourCrosshairscriptontotheGUIgameobject.SelecttheGUIgameobjectandthendragtheaimtexturefoundatfromtheProjectviewtotheCrosshairTexturevariableinthe yandthereshouldbeacrosshairinthecenterofthegame按下運(yùn)行按鈕在游戲屏幕的中心會(huì)出現(xiàn)十字瞄準(zhǔn)Physics物Nowwewantobjectsinourenvironmenttobehaveasnaturallyaspossible,thisisachievedbyaddingphysics.Inthissectionwe’regoingtoaddobjectstotheenvironmentwhichwillmovewhenhitwithourmissile.Firsttherearesomenewtermstoex 節(jié)增加對(duì)象到環(huán)境中,可以用我們的打擊它。首先有一些新的術(shù)語(yǔ)要解釋。Update()更新函Previously,wehaveenteredcodeinsideanUpdatefunction,sothatwecanexecutethatcodeeveryframe.Oneexamplewastodetectiftheuserhadhitthefirebutton.However,framerateisnotaregularvalueasitisdependentonthecomplexityofthesceneetc.Thisirregulartimingbetweenframescanleadtounstablephysics.Therefore,wheneveryouwanttoupdateobjectsinyourgamewhichinvolvephysics(rigidbodies),codeshouldbecedinsideaFixedUpdatefunction.ThedeltaTimevalueinUnityisusedtodeterminethetimetakenbetweenrenderingtwoconsecutiveframes.AgeneraldistinctionbetweenUpdateandFixedUpdatefunctionsisasfollows:以前我們?cè)赨pdate函數(shù)中鍵入代碼,以便我們能在畫(huà)面的每一幀都執(zhí)行它,一個(gè)例子是我們檢測(cè)用戶是否單擊了開(kāi)火按鈕,然而,幀的速率是不規(guī)則的值,它依賴場(chǎng)景等的復(fù)雜程度,這個(gè)介于多幀之間的不規(guī)則變化的時(shí)間可能導(dǎo)致不穩(wěn)定的物理特性,因此,無(wú)論何時(shí)你想更新你的需要物理特性(剛體)的游戲中的對(duì)象時(shí),代碼一定要寫(xiě)到FixedUpate函數(shù)中,在Unity中的deltaTime的值被用來(lái)決定渲染兩個(gè)連續(xù)幀之間所花的時(shí)間。在Update和FixedUpdate函數(shù)之間的一個(gè)普通的區(qū)別像隨后的一樣:Update()–codeinsidethefunctiontypically yerbehavior,gamelogic,etc.valueofdeltaTimeisnotconsistentwhenusedwithinthis在函數(shù)內(nèi)鍵入更新游戲者的行為、游戲邏輯等的代碼,當(dāng)在函數(shù)中使用ate()時(shí)deltaTime的值是不一致的。FixedUpdate()–codeinsidethisfunctiontypicallyupdatesrigidbodiesovertime(physicsbehavior).ThedeltaTimealwaysreturnsthesamevaluewhencalledwithinaFixedUpdate在函數(shù)內(nèi)鍵入剛體隨時(shí)間的變化(物理行為)。當(dāng)調(diào)用一個(gè)FixedUpdatedeltaTime總ThefrequencywithwhichFixedUpdateiscalledisspecifiedbytheFixedTimesteppropertyin optionEdit>ProjectSettings>Timeandcanalsobealtered.Thispropertycontainsthetimeinsecondstogettheframespersecondvalueandtakethereciprocalofthisvalue.FixedUpdate被調(diào)用的頻率是由在菜單選項(xiàng)Edit>ProjectSettings>Time中的固定時(shí)間間隔值并且采用了它的倒數(shù)(F=1/T即物理:頻率=1/周期) WhenmodifyingthevalueforFixedTimestep(effectivelyframespersecond),carefultostrikeabalance;asmallertimestepwillgivemorestablephysics(moreaccuracy),howeverthegameperformancewillsuffer.Ensurethatthegamerunsquicklyandthephysicsseemrealistic.當(dāng)編輯固定時(shí)間間隔(FixedTimestep等效于每幀之間的時(shí)間)時(shí)要取得平衡;一個(gè)小的Thefinaltermtoex ininthissectionisyield.Thiscanbethoughtofasastatementtopauseexecutionofthecurrentfunction.在本節(jié)最后解釋的術(shù)語(yǔ)是yield。這可以看作是一個(gè)暫停執(zhí)行當(dāng)前函數(shù)的Solet’sgetbacktoourgame,whatdowewantto所以讓我們返回我們的游戲,看我們到底想做什Allowtheusertofireamissile(already允許用戶發(fā)射(已經(jīng)做了Ifthemissilecollideswithanotherrigidbody,determineifthereareanyotherobjectsinthevicinitywhichhaverigidbodiesattached.Foreachrigidbodywithinthe oftheexplosion,givethema intheupwardsdirection,causingthemtoreacttothemissile.每個(gè)剛體內(nèi)都有效果影響,給他們一個(gè)向上的力,以使它們對(duì)做出反應(yīng)Let’slookatthecodefortheupdatedExplosionvarexplosionTime=1.0;varvarexplosionTime=1.0;varexplosionRadius=5.0;varexplosionPower=function讓我們看這段更新了的Explosion讓我們看這段更新了的Explosion{//Destroytheexplosioninx//在X秒后銷 //thiswillgivetheparticlesystemandaudioenoughtimeto //將給出足夠的時(shí)間完成運(yùn)行粒子系統(tǒng) 聲Destroy(gameObject,explosionTime//Findallnearbyvarcolliders:Collider[]=Physics.OverlapSphere(transform.position,explosionRadius);Firstwedetermineifthereareanyobjectswithcollidersclosetowherethemissilelanded.TheclassfunctionPhysics.OverlapSphere()takestwoparameters:a3Dpositionandradiusandreturnsanarrayofcolliderswhicharecontainedwithinthedefinedsphere.首先我們確定如果這里有其它任何帶有碰撞器的對(duì)象在降落地方的附近。這個(gè)類函數(shù)Physics.OverlapSphere()帶了兩個(gè)參數(shù):一個(gè)3D位置和半徑并且返回碰撞器數(shù)組,被包含在已定義的sphere球體內(nèi)//Apply//Applytoallsurroundingrigidfor(varhitincollide

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論