您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 经营企划 > 猴子吃香蕉游戏的实现
HowToBuildaMonkeyJumpGameUsingCocos2D,PhysicsEditor&TexturePackerPart3TweetIfyou'renewhere,youmaywanttosubscribetomyRSSfeedorfollowmeonTwitter.Thanksforvisiting!ThisisapostbyspecialcontributorAndreasLoew,thecreatorofTexturePackerandPhysicsEditor.CreatethisverticalscrollingplatformerwithCocos2D!WelcometothefinalpartoftheMonkeyJumptutorial!Inthisseries,wearecreatingafunverticalscrollingplatformerwithCocos2D,TexturePackerandPhysicsEditor.InPartOneonthetutorialseries,weintroducedtheMonkeyJump!gamedesign,createdthespritesheetsandshapesweneeded,andbegancodingthegame.InPartTwo,weaddedourherotothegame,madehimmoveandjump,andaddedsomegameplay.Inthisthirdandfinalpartoftheseries,wewilladdsomeperformanceimprovements,addaHUDLayer,andyes–killthemonkey!:]We’llbestartingwiththeprojectwhereweleftofflasttime.Ifyoudon’thaveitalready,grabthesourcecodeforthistutorialseriesandopenup5-MonkeyJumpAndRun.Allright,timetostopmonkeyingaroundandwrapupthistutorial!:]TooManyObjects!Playingourgameforawhile,you’llseethatitgetsslowerandslower,untilitbecomescompletelyunplayable.There’sareasonforthis–asobjectscontinuetofallfromthesky,oneafteranother,theybumpintotheobjectsalreadylyingaround.AllofthesecollisionshavetobehandledbyBox2d.Iftherearenobjects,therearen*(n-1)possiblecollisionstohandle.Box2duseshashestomakethingsfaster,butyoucanimaginehowdramaticallythenumberofcollisionsincreasesasthenumberofobjectsincreases.Ifyouwatchastatuedrop,you’llseethatnearlytheentirestackbelowmovesandbouncesfromimpulsespassedfromthestatuedownthroughthestackfromoneobjecttoanother.Toimprovethesituation,we’regoingtoconvertobjectswhicharesomedistancebelowthemonkeyintostaticobjects.Thesestaticobjectswillstillletotherobjectspileupabovethem,butthey’llnolongerreacttotheimpact.Asaresult,afallingstatuewillonlyaffectthetopofthestackinsteadofthecompletepile.Box2dallowsobjectstogotosleepwhentheyaren’ttouchedbyotherobjectsforsometime.Wewillusethisfeaturetoimproveperformance.GB2Enginehasaniteratemethodthatcanbeusedtoiterateallobjectswithablock.Wewilluseittocreatearoutinethatchecksthey-coordinatesofallobjectsandputstosleepanythatareacertaindistancebelowthemonkey.AddthefollowingcodetotheendoftheupdateselectorinGameLayer.mm://10-Iterateoverobjectsandturnobjectsintostaticobjects//iftheyaresomedistancebelowthemonkeyfloatpruneDistance=240/PTM_RATIO;floatprune=[monkeyphysicsPosition].y-pruneDistance;[[GB2EnginesharedInstance]iterateObjectsWithBlock:^(GB2Node*n){if([nisKindOfClass:[Objectclass]]){Object*o=(Object*)n;floaty=[ophysicsPosition].y;if(yprune){//setobjecttostatic//ifitisbelowthemonkey[osetBodyType:b2_staticBody];}}}];Compileandtest.Notethattherearestillsomesituationswherethingswon’tworkasexpected.Forexample,ifagroupofobjectspileuplikeatower,andthemonkeyclimbsontothepile,itmighthappenthatadroppingobjectreachesthepruneDistanceandisconvertedintoastaticobjectinmid-air.Thesolutionisquitesimple:onlyconvertobjectstostaticiftheirspeedislow.Changethesecondifconditionintheabovecodeto:if((yprune)&&([olinearVelocity].LengthSquared()0.1)){...}Compileandtest.Looksgood,doesn’tit?CaughtinaTrap捕捉一个陷阱There’sstillanissuethough–themonkeymightstillgetcaughtunderapileofobjects.Itemspileup这里还有一个问题—猴子的周围有一堆对象,aroundhim,andhe’snotstrongenoughtobreakfreeiftherearetoomanyobjectsabovehim.Thereareseveralwaystodealwiththissituation.Oneistosimplylethimdieifhe’sstuck.Anothersolutionisto“teleport”themonkeyabovetheobjectsandlethimgoonplaying.Thatsoundsfun,let’sdothat!Tomakethiswork,wemustbesurethatthemonkeyteleportsaboveallobjects.Otherwise,hispositionmightplacehimdirectlyinsideanotherobjectandhe’llneverbreakfree!GointoGameLayer.handaddamembervariable:floathighestObjectY;//ypositionofthehighestobjectAndmakeitapropertybyaddingthefollowinglineabovethe“scene”methoddeclaration:@property(nonatomic,readonly)floathighestObjectY;NowswitchtoGameLayer.mmandsynthesizetheobjectbyaddingthislinejustbelowthe“@implementation”line:@synthesizehighestObjectY;Then,replacesection#10inupdatewiththefollowing://10-Iterateoverobjectsandturnobjectsintostaticobjects//iftheyaresomedistancebelowthemonkeyfloatpruneDistance=240/PTM_RATIO;floatprune=[monkeyphysicsPosition].y-pruneDistance;highestObjectY=0.0f;[[GB2EnginesharedInstance]iterateObjectsWithBlock:^(GB2Node*n){if([nisKindOfClass:[Objectclass]]){Object*o=(Object*)n;floaty=[ophysicsPosition].y;//recordthehighestobjectif((yhighestObjectY)&&([oactive])){highestObjectY=y;}if((yprune)&&([olinearVelocity].LengthSquared()0.1)){//setobjecttostatic//ifitisbelowthemonkey[osetBodyType:b2_staticBody];}}}];ThenewcodedeterminesthehighestobjectlocationbyresettingthehighestObjectYwitheverynewcheck.Notethatitonlychecksactiveobjects.Otherwise,thehighestobjectwillalwaysbetheobjectthatiswaitingtodrop.SwitchtoMonkey.handaddanewmember:intstuckWatchDogFrames;//countertodetectifmonkeyisstuckNowlet’steleportthemonkeyabovethehighestobject’spositionifhe’sbeenstuckwithanobjectabovehisheadforacertainamountoftime.AaddthefollowingtotheendoftheupdateCCFromPhysicsselector://8-Checkifmonkeyisstuckif(numHeadCo
本文标题:猴子吃香蕉游戏的实现
链接地址:https://www.777doc.com/doc-3601828 .html