猴子吃香蕉游戏的实现.docx
- 文档编号:23211003
- 上传时间:2023-05-15
- 格式:DOCX
- 页数:33
- 大小:1.94MB
猴子吃香蕉游戏的实现.docx
《猴子吃香蕉游戏的实现.docx》由会员分享,可在线阅读,更多相关《猴子吃香蕉游戏的实现.docx(33页珍藏版)》请在冰豆网上搜索。
猴子吃香蕉游戏的实现
HowToBuildaMonkeyJumpGameUsingCocos2D,PhysicsEditor&TexturePackerPart3
Tweet
Ifyou'renewhere,youmaywanttosubscribetomy RSSfeed orfollowmeon Twitter.Thanksforvisiting!
Thisisapostbyspecialcontributor AndreasLoew,thecreatorofTexturePackerandPhysicsEditor.
CreatethisverticalscrollingplatformerwithCocos2D!
WelcometothefinalpartoftheMonkeyJumptutorial!
Inthisseries,wearecreatingafunverticalscrollingplatformerwithCocos2D, TexturePacker and PhysicsEditor.
In PartOne onthetutorialseries,weintroducedtheMonkeyJump!
gamedesign,createdthespritesheetsandshapesweneeded,andbegancodingthegame.
In PartTwo,weaddedourherotothegame,madehimmoveandjump,andaddedsomegameplay.
Inthisthirdandfinalpartoftheseries,wewilladdsomeperformanceimprovements,addaHUDLayer,andyes–killthemonkey!
:
]
We’llbestartingwiththeprojectwhereweleftofflasttime.Ifyoudon’thaveitalready,grabthe sourcecode forthistutorialseriesandopenup5-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.
Addthefollowingcodetotheendofthe update selectorin GameLayer.mm:
//10-Iterateoverobjectsandturnobjectsintostaticobjects
//iftheyaresomedistancebelowthemonkey
floatpruneDistance=240/PTM_RATIO;
floatprune=[monkeyphysicsPosition].y-pruneDistance;
[[GB2EnginesharedInstance]iterateObjectsWithBlock:
^(GB2Node*n)
{
if([nisKindOfClass:
[Objectclass]])
{
Object*o=(Object*)n;
floaty=[ophysicsPosition].y;
if(y { //setobjecttostatic //ifitisbelowthemonkey [osetBodyType: b2_staticBody]; } } } ]; Compileandtest.Notethattherearestillsomesituationswherethingswon’tworkasexpected.Forexample,ifagroupofobjectspileuplikeatower,andthemonkeyclimbsontothepile,itmighthappenthatadroppingobjectreachesthepruneDistanceandisconvertedintoastaticobjectinmid-air. Thesolutionisquitesimple: onlyconvertobjectstostaticiftheirspeedislow.Changethesecondifconditionintheabovecodeto: if((y ([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! Gointo GameLayer.h andaddamembervariable: floathighestObjectY;//ypositionofthehighestobject Andmakeitapropertybyaddingthefollowinglineabovethe“scene”methoddeclaration: @property(nonatomic,readonly)floathighestObjectY; Nowswitchto GameLayer.mm andsynthesizetheobjectbyaddingthislinejustbelowthe“@implementation”line: @synthesizehighestObjectY; Then,replacesection#10in update withthefollowing: //10-Iterateoverobjectsandturnobjectsintostaticobjects //iftheyaresomedistancebelowthemonkey floatpruneDistance=240/PTM_RATIO; floatprune=[monkeyphysicsPosition].y-pruneDistance; highestObjectY=0.0f; [[GB2EnginesharedInstance]iterateObjectsWithBlock: ^(GB2Node*n) { if([nisKindOfClass: [Objectclass]]) { Object*o=(Object*)n; floaty=[ophysicsPosition].y; //recordthehighestobject if((y>highestObjectY)&&([oactive])) { highestObjectY=y; } if((y ([olinearVelocity].LengthSquared()<0.1)) { //setobjecttostatic //ifitisbelowthemonkey [osetBodyType: b2_staticBody]; } } } ]; ThenewcodedeterminesthehighestobjectlocationbyresettingthehighestObjectYwitheverynewcheck.Notethatitonlychecksactiveobjects.Otherwise,thehighestobjectwillalwaysbetheobjectthatiswaitingtodrop. Switchto Monkey.h andaddanewmember: intstuckWatchDogFrames;//countertodetectifmonkeyisstuck Nowlet’steleportthemonkeyabovethehighestobject’spositionifhe’sbeenstuckwithanobjectabovehisheadforacertainamountoftime.Aaddthefollowingtotheendofthe updateCCFromPhysics selector: //8-Checkifmonkeyisstuck if(numHeadContacts>0) { stuckWatchDogFrames--; if(stuckWatchDogFrames==0) { //teleportthemonkeyabovethehighestobject [selfsetPhysicsPosition: b2Vec2([selfphysicsPosition].x, gameLayer.highestObjectY+2.0)]; } } else { //restartwatchdog stuckWatchDogFrames=120;//2secondsat60fps } Compileandrun.That’smuchbetter! Now,ifthemonkeyiscaughtinatrapandhecan’tpushhiswayout,hewillbemagicallyfreed. Thereareotherwaystodetectifthemonkeyiscaught.Forexample,wecouldcheckhowhightheobjectsarepiled,orifthemonkey’sspeedislowforacertainamountoftime.Feelfreetotryoutotherdetectionmethodstoseewhichoneworksbestforyou. PuttingthePainonOurHero Playthegameforabitandyou’llrealizethatthereisn’tmuchchallengetothisgame–themonkeyclimbsbutdoesn’ttakeanydamage.Let’schangethat. Open Monkey.h andaddanewvariablecalledhealthtotheMonkeyclass. floathealth; Alsoaddpropertiestoaccessthehealthlevelandtodetectifthemonkeyisdead: @property(readonly)floathealth; @property(readonly)boolisDead; Finally,addadefineforthemaximumhealth,atthetopofthefilebelowtheimportstatements: #defineMONKEY_MAX_HEALTH100.0f Nowswitchto Monkey.mm andsynthesizethehealthproperty: @synthesizehealth; ImplementtheisDeadpropertybyaddingthefollowingcodeabovethe walk method: -(bool)isDead { returnhealth<=0.0f; } Asyou’llnotice,wedecideifthemonkeyisdeadornotbasedonifhishealthislessthan0ornot. Intheinitselector,initializethehealthwiththemaximumvaluebyaddingthisbelowthegamelayerstoragecode: //sethealth health=MONKEY_MAX_HEALTH; Nowlet’sputthehurtonthemonkeybymodifyingthesectionwiththeheadcollisioninbeginContactWithObject: elseif([fixtureIdisEqualToString: @"head"]) { numHeadContacts++; floatvY=[contact.otherObjectlinearVelocity].y; if(vY<0) { constfloathurtFactor=1.0; //reducehealth health+=vY*[contact.otherObjectmass]*hurtFactor; if(self.isDead) { //setmonkeytocollidewithflooronly [selfsetCollisionMaskBits: 0x0001]; //releaserotationlock [selfsetFixedRotation: NO]; //changeanimationphasetodead [selfsetDisplayFrameNamed: @"monkey/dead.png"]; } } } Basically,themonkeyshouldgethurtwhenanobjectcollideswithhishead.Calculatethedamageusingtheobject’sverticalvelocityandmass,andreducethemonkey’shealthbythatamount.Thiscausesdamagefromfast-droppingobjects,butdoesn’tharmthemonkeyifanobjectisrestingabovehishead.NoticethatIalsoaddedahurtFactorsothatyoucanadjusthowmuchthemonkeyishurt. Ifthemonkeydies,heshoulddropfromthescene.Inthiscase,we’llsimplydeleteallthemonkey’scollisionflagsexceptforthefloor.Thiswillmakethemonkeyfalldeadonthefloor.We’llreleasetherotationlocktolethimlieonthefloor,andchangethemonkey’sspritetodead.png. Deadmonkeyscan’tjump–sochangethecodeinthemonkey’sjumpselectortoignorescreentapsifthemonkeyisdead: -(void)jump { if((numFloorContacts>0)&&(! self.isDead)) { ... Disablethe updateCCFromPhysics contentsbychangingsection#1,aswell: -(void)updateCCFromPhysics { //1-Callthesuperclass [superupdateCCFromPhysics]; //he'sdead–sojustlethimbe! if(self.isDead) { return; } ... Compileandrun,andnowyoucanbringoutyourevilside–killthemonkey! : ] RestartingtheGame Nowthemonkeydies,buttheobjectskeepfallingandthere’snowaytorestartthegame. Iwouldsuggestrestartingtwosecondsafterthemonkey’
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 猴子 香蕉 游戏 实现