Anda di halaman 1dari 19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

HigherOrderFun
GameDesign&GameProgramming

Theguidetoimplementing2D
platformers
Havingpreviouslybeendisappointedbytheinformationavailableonthetopic,thisismyattempt
atcategorizingdifferentwaystoimplement2Dplatformgames,listtheirstrengthsand
weaknesses,anddiscusssomeimplementationdetails.
Thelongtermgoalistomakethisanexhaustiveandcomprehensibleguidetothe
implementationof2Dplatformgames.Ifyouhaveanysortoffeedback,correction,request,or
additionpleaseleaveitinthecomments!
Disclaimer:someoftheinformationpresentedherecomesfromreverseengineeringthe
behaviorofthegame,notfromitscodeorprogrammers.Itspossiblethattheyarenot
ACTUALLYimplementedinthisway,andmerelybehaveinanequivalentway.Alsonotethattile
sizesareforthegamelogic,graphicaltilesmightbeofadifferentsize.

FourWaysofImplementing
Icanthinkoffourmajorwaysinwhichaplatformgamecanbeimplemented.Fromsimplestto
mostcomplicated,theyare:

Type#1:Tilebased(pure)
Charactermovementislimitedtotiles,soyoucanneverstandhalfwaybetweentwotiles.
Animationsmaybeusedtocreatetheillusionofsmoothmovement,butasfarasthegamelogicis
concerned,theplayerisalwaysrightontopofaspecifictile.Thisistheeasiestwaytoimplement
aplatformgame,butitimposesheavyrestrictionsonthecontrolofcharacter,makingit
unsuitablefortraditionalactionbasedplatformers.Itis,however,popularwithpuzzleand
cinematographicplatformers.

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%2

1/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

Flashback,shownwithtileboundaries
Examples:PrinceofPersia,TokiTori,LodeRunner,Flashback
Howitworks
Themapisagridoftiles,eachonestoringinformationsuchaswhetheritsanobstacleornot,
whatimagetouse,whatkindoffootstepsoundtouse,andsoon.Theplayerandothercharacters
arerepresentedbyasetofoneormoretilesthatmovetogether.InLodeRunner,forexample,
theplayerisasingletile.InTokiTori,theplayeris22tiles.InFlashback,whichisunusualdue
tothesmallersizeofitstiles,theplayeristwotileswideandfivetilestall(seeimageabove)when
standing,butonlythreetilestallwhencrouching.
Inthiskindofgame,theplayerwillrarelyifeverbemovingdiagonally,but,ifheis,the
movementcanbedecomposedintwoseparatesteps.Likewise,hewilllikelyonlymoveonetileat
once,butmultitilemovementcanbedoneasmultiplestepsofonetile,ifneeded(inFlashback,
youalwaysmovetwotilesatonce).Thealgorithmisthenasfollows:
1. Createacopyofthecharacterwherehedliketomoveto(e.g.,ifmovingonetiletotheright,
makeacopywhereeverytileofthecharacterisshifted1tiletotheright)
2. Checkthatcopyforintersectionwiththebackgroundandothercharacters.
3. Ifanintersectionisfound,thecharactersmovementisblocked.Reactaccordingly.
4. Otherwise,thepathisclear.Movecharacterthere,optionallyplayingananimationsothe
transitionlookssmooth.
Thiskindofmovementisveryillsuitedfortraditionalarcshapedjumpssogamesinthisgenre
oftenhavenojumpatall(TokiTori,LodeRunner),oronlyallowverticalorhorizontaljumps
(PrinceofPersia,Flashback),whicharenothingbutspecialcasesoflinearmovement.
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%2

2/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

Advantagesofthissystemincludesimplicityandprecision.Sincethegamesaremore
deterministic,glitchesaremuchlesslikely,andthegameplayexperienceismorecontrolled,with
lessofaneedtotweakvaluesdependingoncircumstances.Implementingcertainmechanics(such
asgrabbingledgesandonewayplatforms)becomesabreeze,comparedtomorecomplex
movementstylesallyouhavetodoischeckwhethertheplayertilesandthebackgroundtiles
arealignedintheonespecificwaythatallowsforagivenaction.
Inprinciple,thissystemdoesntallowstepsoflessthanonetile,butthatcanbemitigatedinafew
differentways.Forexample,thetilescanbeabitsmallerthantheplayer(say,aplayeris26
tiles),oryoucanallowavisualonlymovementtotakeplaceinsideagiventile,withoutaffecting
thelogic(whichisthesolutionthatIbelievethatLodeRunnerTheLegendReturnstakes).

Type#2:TileBased(Smooth)
Collisionisstilldeterminedbyatilemap,butcharacterscanmovefreelyaroundtheworld
(typicallywith1pxresolution,alignedtointegers,butseethenoteattheendofarticleregarding
smoothingofmovement).Thisisthemostcommonformofimplementingplatformersin8bit
and16bitconsoles,andremainspopulartoday,asitisstilleasytoimplementandmakeslevel
editingsimplerthanmoresophisticatedtechniques.Italsoallowsforslopesandsmoothjump
arcs.
Ifyoureunsurewhichtypeofplatformeryouwanttoimplement,andyouwanttodoanaction
game,Isuggestgoingforthisone.Itsveryflexible,relativelyeasytoimplement,andgivesyou
themostcontrolofallfourtypes.Itsnowonderthatthemajorityofthebestactionplatformers
ofalltimearebasedonthistype.

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%2

3/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

MegaManX,shownwithtileboundariesandplayerhitbox.
Examples:SuperMarioWorld,SonictheHedgehog,MegaMan,SuperMetroid,Contra,Metal
Slug,andpracticallyeveryplatformerofthe16bitera

Howitworks
Mapinformationisstoredinthesamewayaswiththepuretiletechnique,thedifferenceis
merelyinhowthecharactersinteractwiththebackground.Thecharacterscollisionhitboxisnow
anAxisAlignedBoundingBox(AABB,thatis,arectanglethatcannotberotated),andare
typicallystillanintegermultipleoftilesize.Commonsizesincludeonetilewideandone(small
Mario,morphballSamus),two(bigMario,MegaMan,crouchedSamus)orthree(standing
Samus)tilestall.Inmanycases,thecharacterspriteitselfislargerthanthelogicalhitbox,asthis
makesforamorepleasantvisualexperienceandfairergameplay(itsbetterfortheplayerto
avoidgettinghitwhenheshouldhavethanforhimtogethitwhenheshouldnothave).Inthe
imageabove,youcanseethatthespriteforXissquareish(infact,istwotileswide),buthis
hitboxisrectangular(onetilewide).
Assumingthattherearenoslopesandonewayplatforms,thealgorithmisstraightforward:
1. DecomposemovementintoXandYaxes,steponeatatime.Ifyoureplanningon
implementingslopesafterwards,stepXfirst,thenY.Otherwise,theordershouldntmatter
much.Then,foreachaxis:
2. Getthecoordinateoftheforwardfacingedge,e.g.:Ifwalkingleft,thexcoordinateofleftof
boundingbox.Ifwalkingright,xcoordinateofrightside.Ifup,ycoordinateoftop,etc.
3. Figurewhichlinesoftilestheboundingboxintersectswiththiswillgiveyouaminimum
andmaximumtilevalueontheOPPOSITEaxis.Forexample,ifwerewalkingleft,perhaps
theplayerintersectswithhorizontalrows32,33and34(thatis,tileswithy=32*TS,y=33
*TS,andy=34*TS,whereTS=tilesize).
4. Scanalongthoselinesoftilesandtowardsthedirectionofmovementuntilyoufindthe
closeststaticobstacle.Thenloopthrougheverymovingobstacle,anddeterminewhichisthe
closestobstaclethatisactuallyonyourpath.
5. Thetotalmovementoftheplayeralongthatdirectionisthentheminimumbetweenthe
distancetoclosestobstacle,andtheamountthatyouwantedtomoveinthefirstplace.
6. Moveplayertothenewposition.Withthisnewposition,steptheothercoordinate,ifstillnot
done.

Slopes

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%2

4/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

MegaManX,withslopetileannotations
Slopes(thetilespointedbygreenarrowsontheimageabove)canbeverytricky,becausetheyare
obstacles,andyetstillallowthecharactertomoveintotheirtile.Theyalsocausemovement
alongtheXaxistoadjustpositionontheYaxis.Onewaytodealwiththemistohavethetilestore
theflooryofeitherside.Assumingacoordinatesystemwhere(0,0)isattopleft,thenthetile
justleftofX(firstslopetile)is{0,3}(left,right),thentheonehestandsonis{4,7},then{8,11},
then{12,15}.Afterthat,thetilesrepeat,withanother{0,3},etc,andthenwehaveasteeper
slope,composedoftwotiles:{0,7}and{8,15}.

DetailedViewofthe{4,7}tile
ThesystemthatImgoingtodescribeallowsarbitraryslopes,thoughforvisualreasons,those
twoslopesarethemostcommon,andresultinatotalof12tiles(the6describedpreviously,and
theirmirrorings).Thecollisionalgorithmchangesasfollowsforhorizontalmovement:
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%2

5/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

MakesurethatyoustepXpositionbeforeYposition.
Duringcollisiondetection(4above),theslopeonlycountsasacollisionifitsclosestedgeis
thetaller(smallerycoordinate)one.Thiswillpreventcharactersfrompoppingthroughthe
slopefromtheoppositeside.
Youmightwanttoforbidslopestostophalfwaythrough(e.g.ona{4,7}tile).This
restrictionisadoptedbyMegaManXandmanyothergames.Ifyoudont,youhavetodeal
withthemorecomplicatedcaseoftheplayerattemptingtoclimbfromthelowersideofthe
slopetileonewaytodealwiththisistopreprocessthelevel,andflagallsuchoffending
tiles.Then,oncollisiondetection,alsocountitasacollisionfromthelowersideifthe
playerslowestycoordinateisgreater(thatis,below)thetilesoffsetedge(tilecoord*tile
size+floory).
Afullobstacletileadjacenttotheslopethecharacteriscurrentlyonshouldnotbeconsidered
forcollisionifitconnectstotheslope,thatis,ifthecharacter(thatis,hisbottomcenter
pixel)isona{0,*}slope,ignorelefttile,and,ifona{*,0}slope,ignoretherighttile.You
mayhavetodothisformoretilesifyourcharacteriswiderthantwotilesyoumightsimply
skipcheckingontheentirerowiftheplayerismovingtowardstheuppersideofslope.The
reasonforthisistopreventthecharacterfromgettingstuckatthosetiles(highlightedyellow
above)whilestillclimbingtheslope,ashisfootwillstillbebelowthesurfacelevelbythe
timehecomesintocontactwiththeotherwisesolidtile.
Andforverticalmovement:
Ifyourelettinggravitydoitsjobfordownhillmovement,makesurethattheminimum
gravitydisplacementiscompatiblewithslopeandhorizontalvelocity.Forexample,ona4:1
slope(as{4,7}above),thegravitydisplacementmustbeatleast1/4ofthehorizontal
velocity,roundedup.Ona2:1slope(suchas{0,7}),atleast1/2.Ifyoudontensurethis,the
playerwillmovehorizontallyrightofftherampforawhile,untilgravitycatchesupanddrags
himdown,makinghimbounceontheramp,insteadofsmoothlydescendingit.
Analternativetousinggravityistocomputehowmanypixelsabovefloortheplayerwas
beforemovement,andhowmanyitisafterwards(usingtheformulabelow),andadjusthis
positionsotheyrethesame.
Whenmovingdown,insteadofconsideringaslopetilestopedgeasitscollisionboundary,
instead,computeitsfloorcoordinateatthecurrentverticalline,andusethat.Todothat,find
the[0,1]valuewhichrepresentstheplayersxpositionontile(0=left,1=right)anduseitto
linearlyinterpolatethefloorYvalues.Thecodewilllooksomethinglike:
1
2

floatt=float(centerXtileX)/tileSize;
floatfloorY=(1t)*leftFloorY+t*rightFloorY;

Whenmovingdown,ifmultipletilesonthesameYcoordinateareobstaclecandidates,and
theoneontheXcoordinateoftheplayerscenterisaslopetile,usethatone,andignorethe
resteventhoughtheothersaretechnicallycloser.Thisensuresproperbehaviouraround
theedgesofslopes,withthecharacteractuallysinkingonacompletelysolidtilebecauseof
theadjacentslope.

Onewayplatforms

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%2

6/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

SuperMarioWorld,showingMariofallingthrough(left)andstandingon(right)thesameone
wayplatform
Onewayplatformsareplatformsthatyoucanstepon,butyoucanalsojumpthroughthem.In
otherwords,theycountasanobstacleifyourealreadyontopofthem,butareotherwise
traversable.Thatsentenceisthekeytounderstandingtheirbehavior.Thealgorithmchangesas
follows:
Onthexaxis,thetileisneveranobstacle
Ontheyaxis,thetileisonlyanobstacleif,priortothemovement,theplayerwasentirely
aboveit(thatis,bottommostcoordinateofplayerwasatleastonepixelabovetopmost
coordinateofonewayplatform).Tocheckforthis,youwillprobablywanttostorethe
originalplayerpositionbeforedoinganystepping.
Itmightbetemptingtohaveitactasanobstacleiftheplayersyspeedispositive(thatis,ifthe
playerisfalling),butthisbehavioriswrong:itspossiblefortheplayertojumpsoheoverlapsthe
platform,butthenfallsdownagainwithouthavinghisfeetreachtheplatform.Inthatcase,he
shouldstillfallthrough.
Somegamesallowtheplayertojumpdownfromsuchplatforms.Thereareafewwaystodo
this,buttheyareallrelativelysimple.Youcould,forexample,disableonewayplatformsfora
singleframeandensurethatyspeedisatleastone(sohellbeclearoftheinitialcollision
conditiononthenextframe),oryoucouldcheckifhesstandingexclusivelyononeway
platforms,and,ifso,manuallymovetheplayeronepixeltothebottom.

Ladders

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%2

7/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

MegaMan7,withtileboundaries,highlightedladdertiles,andplayerladderhitbox.
Laddersmightseemcomplicatedtoimplement,buttheyaresimplyanalternatestatewhen
youreinaladder,youignoremostofthestandardcollisionsystem,andreplaceitwithanewset
ofrules.Laddersaretypicallyonetilewide.
Youcanusuallyentertheladderstateintwoways:
Haveyourcharacterhitboxoverlapwiththeladder,eitherongroundoronair,andhitup
(somegamesalsoallowyoutohitdown)
Haveyourcharacterstandontopofaladdertoptile(whichisoftenaonewayplatformtile
aswell,soyoucanwalkontopofit),andhitdown.
Thishastheeffectofimmediatelysnappingtheplayersxcoordinatetoalignwiththeladdertiles,
and,ifgoingdownfromthetopofladder,moveycoordinatesoplayerisnowinsidetheactual
ladder.Atthispoint,somegameswilluseadifferenthitboxforthepurposesofdetermining
whethertheplayerisstillontheladder.MegaMan,forexample,seemstouseasingletile
(equivalenttotoptileoftheoriginalcharacter,highlightedinredintheimageabove).
ThereareafewdifferentwaysofLEAVINGtheladder:
Reachingthetopoftheladder.Thiswillusuallypromptananimationandmovetheplayer
severalpixelsupiny,sohesnowstandingontopoftheladder.
Reachingthebottomofahangingladder.Thiswillcausetheplayertosimplyfall,although
somegameswontlettheplayerleavetheladderinthisway.
Movingleftorright.Ifthereisnoobstacleonthatside,theplayermaybeallowedtoleave
thatway.
Jumping.Somegamesallowyoutoreleasetheladderbydoingthis.
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%2

8/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

Whileontheladder,thecharactersmovementchangesso,typically,allhecandoismoveupand
down,andsometimesattack.

Stairs

Castlevania:DraculaX,withtileboundaries
Stairsareavariationofladders,seeninfewgames,butnotablyintheCastlevaniaseries.The
actualimplementationisverysimilartothatofladders,withafewexceptions:
Theplayermovestilebytileorhalftilebyhalftile(asinDraculaX)
EachstepcausestheplayertobeshiftedsimultaneouslyonXandYcoordinates,bya
presetamount.
Initialoverlappingdetectionwhengoingupmightlookonthetileaheadinsteadofjustthe
currentoverlapone.
Othergamesalsohavestairsthatbehavelikeslopes.Inthatcase,theyaresimplyavisualfeature.

MovingPlatforms

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%2

9/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

SuperMarioWorld
Movingplatformscanseemalittletricky,butareactuallyfairlysimple.Unlikenormalplatforms,
theycannotberepresentedbyfixedtiles(forobviousreasons),andinsteadshouldbe
representedbyanAABB,thatis,arectanglethatcannotberotated.Itisanormalobstacleforall
collisionpurposes,andifyoustophere,youllhaveveryslipperymovingplatforms(thatis,they
workasintended,exceptthatthecharacterdoesnotmovealongitonhisown).
Thereareafewdifferentwaystoimplementthat.Onealgorithmisasfollows:
Beforeanythingonthesceneisstepped,determinewhetherthecharacterisstandingona
movingplatform.Thiscanbedonebychecking,forexample,whetherhiscenterbottompixel
isjustonepixelabovethesurfaceoftheplatform.Ifitis,storeahandletotheplatformand
itscurrentpositioninsidethecharacter.
Stepallmovingplatforms.Makesurethatthishappensbeforeyoustepcharacters.
Foreverycharacterthatsstandingonamovingplatform,figurethedeltapositionofthe
platform,thatis,howmuchithasmovedalongeachaxis.Now,shiftthecharacterbythe
sameamount.
Stepthecharactersasusual.

OtherFeatures

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%

10/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

SonictheHedgehog2
Othergameshavemorecomplicatedandexclusivefeatures.SonictheHedgehogseriesisnotable
forthis.Thosearebeyondthescopeofthisarticle(andmyknowledge,forthatmatter!),but
mightbesubjectofafuturearticle.

Type#3:Bitmask
SimilartoTileBased(Smooth),butinsteadofusinglargetiles,animageisusedtodetermine
collisionforeachpixel.Thisallowsfinerdetailing,butsignificantlyincreasescomplexity,memory
usage,andrequiressomethingakintoanimageeditortocreatelevels.Italsooftenimpliesthat
tileswontbeusedforvisuals,andmaythereforerequirelarge,individualartworkforeachlevel.
Duetothoseissues,thisisarelativelyuncommontechnique,butcanproducehigherquality
resultsthantilebasedapproaches.Itisalsosuitablefordynamicenvironmentssuchasthe
destructiblescenariosinWormsasyoucandrawintothebitmasktochangethescenario.

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%

11/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

WormsWorldParty,featuringdestructibleterrain
Examples:Worms,TalbotsOdyssey

Howitworks
Thebasicideaisverysimilartothetile(smooth)algorithmyoucansimplyconsidereachpixel
tobeatile,andimplementtheexactsamealgorithm,andeverythingwillwork,withonemajor
exceptionslopes.Sinceslopesarenowimplicitlydefinedbythepositioningbetweennearby
tiles,theprevioustechniquedoesntwork,andamuchmorecomplexalgorithmhastobeusedin
itsplace.Otherthings,suchasladders,alsobecometrickier.

Slopes

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%

12/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

TalbotsOdyssey,withthecollisionbitmaskoverlaidontopofthegame.
Slopesaretheprimaryreasonwhythistypeofimplementationisveryhardtogetright.
Unfortunately,theyarealsoprettymuchmandatory,asitdmakenosensetousethis
implementationwithoutslopes.Often,theyrethereasonwhyyoureevenusingthissystem.
Thisis,roughly,thealgorithmusedbyTalbotsOdyssey:
Integrateaccelerationandvelocitytocomputethedesireddeltapositionvector(howmuch
tomoveineachaxis).
Stepeachaxisseparately,startingwiththeonewiththelargestabsolutedifference.
Forthehorizontalmovement,offsettheplayerAABBby3pixelstothetop,sohecanclimb
slopes.
Scanahead,bycheckingagainstallvalidobstaclesandthebitmaskitself,todeterminehow
manypixelsitisabletomovebeforehittinganobstacle.Movetothisnewposition.
Ifthiswashorizontalmovement,moveasmanypixelsupasnecessary(whichshouldbeupto
3)tomakeupforslope.
If,attheendofthemovement,anypixelofthecharacterisoverlapingwithanyobstacle,
undothemovementonthisaxis.
Regardlessofresultoflastcondition,proceedtodothesamefortheotheraxis.
Becausethissystemhasnodistinctionbetweenmovingdownbecauseyouregoingdownhillor
becauseyourefalling,yourelikelytoneedasystemcountinghowmanyframesitsbeensincethe
characterlasttouchedthefloor,forpurposesofdeterminingwhetheritcanjumpandchanging
animation.ForTalbot,thisvalueis10frames.
Anothertrickhereisefficientlycomputinghowmanypixelsitcanmovebeforehittingsomething.
Thereareotherpossiblecomplicatingfactors,suchasonewayplatforms(dealtintheexactsame
wayasfortiled(smooth))andslidingdownsteepinclines(whichisfairlycomplexandbeyondthe
scopeofthearticle).Ingeneral,thistechniquerequiresalotoffinetuning,andisintrinsicallyless
stablethantilebasedapproaches.Ionlyrecommenditifyouabsolutelymusthavedetailed
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%

13/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

terrain.

Type#4:Vectorial
Thistechniqueusesvectorialdata(linesorpolygons)todeterminetheboundariesofcollision
areas.Verydifficulttoimplementproperly,itisneverthelessincreasinglypopulardueto
theubiquityofphysicsengines,suchasBox2D,whicharesuitableforimplementingthis
technique.Itprovidesbenefitssimilartothebitmasktechnique,butwithoutmajormemory
overhead,andusingaverydifferentwayofeditinglevels.

Braid(leveleditor),withvisiblelayers(top)andthecollisionpolygons(bottom)
Examples:Braid,Limbo

Howitworks
Therearetwogeneralwaysofapproachingthis:
Resolvemovementandcollisionsyourself,similartothebitmaskmethod,butusingpolygon
anglestocomputedeflectionandhaveproperslopes.
Useaphysicsengine(e.g.Box2D)
Obviously,thesecondismorepopular(thoughIsuspectthatBraidwentforthefirst),both
becauseitiseasierandbecauseitallowsyoutodomanyotherthingswithphysicsinthegame.
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%

14/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

Unfortunately,inmyopinion,onehastobeverycarefulwhengoingthisroute,toavoidmaking
thegamefeellikeageneric,uninterestingphysicsplatformer.

Compoundobjects
Thisapproachhasitsownuniqueproblems.Itmaysuddenlybedifficulttotellwhethertheplayer
isactuallystandingonthefloor(duetoroundingerrors),orwhetheritshittingawallorsliding
downasteepincline.Ifusingaphysicsengine,frictioncanbeanissue,asyoullwantfrictiontobe
highonthefoot,butlowonthesides.
Therearedifferentwaystodealwiththose,butapopularsolutionistodividethecharacterinto
severaldifferentpolygons,eachwithdifferentrolesassociated:soyoud(optionally)havethe
maincentralbody,thenathinrectangleforfeet,andtwothinrectanglesforsides,andanother
forheadorsomesimilarcombination.Sometimestheyaretaperedtoavoidgettingcaughtinto
obstacles.Theycanhavedifferentphysicsproperties,andcollisioncallbacksonthosecanbeused
todeterminethestatusofcharacter.Formoreinformation,sensors(noncollidingobjectsthat
arejustusedtocheckforoverlap)canbeused.Commoncasesincludedetermininingwhether
werecloseenoughtothefloortoperformajump,orifthecharacterispushingagainstawall,
etc.

GeneralConsiderations
Regardlessofthetypeofplatformmovementthatyouhavechosen(exceptperhapsfortype#1),
afewgeneralconsiderationsapply.

Acceleration

SuperMarioWorld(lowacceleration),SuperMetroid(midacceleration),MegaMan7(high
acceleration)
Oneofthefactorsthataffectsthefeelofaplatformerthemostistheaccelerationofthe
character.Accelerationistherateofchangeinspeed.Whenitislow,thecharactertakesalong
timetoreachitsmaximumvelocity,ortocometoahaltaftertheplayerletsgoofcontrols.This
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%

15/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

makesthecharacterfeelslippery,andcanbehardtomaster.Thismovementismostcommonly
associatedwiththeSuperMarioseriesofgames.Whentheaccelerationishigh,thecharacter
takesverylittle(ornotime)togofromzerotomaximumspeedandback,resultinginveryfast
responding,twitchycontrols,asseenintheMegaManseries(IbelievethatMegaManactually
employsinfiniteacceleration,thatis,youreeitherstoppedoronfullspeed).
Evenifagamehasnoaccelerationonitshorizontalmovement,itislikelytohaveatleastsome
forthejumparcsotherwisetheywillbeshapedliketriangles.

Howitworks
Implementingaccelerationisactuallyfairlysimple,butthereareafewtrapstowatchoutfor.
DeterminexTargetSpeed.Thisshouldbe0iftheplayerisnottouchingthecontrols,
maxSpeedifpressingleftor+maxSpeedifpressingright.
DetermineyTargetSpeed.Thisshouldbe0iftheplayerisstandingonaplatform,
+terminalSpeedotherwise.
Foreachaxis,acceleratethecurrentspeedtowardstargetspeedusingeitherweighted
averagingoraddingacceleration.
Thetwoaccelerationmethodsareasfollows:
Weightedaveraging:accelerationisanumber(a)from0(nochange)to1(instant
acceleration).Usethatvaluetolinearlyinterpolatebetweentargetandcurrentspeed,andset
theresultascurrentspeed.
1
2
3

vector2fcurSpeed=a*targetSpeed+(1a)*curSpeed;
if(fabs(curSpeed.x)<threshold)curSpeed.x=0;
if(fabs(curSpeed.y)<threshold)curSpeed.y=0;
Addingacceleration:Welldeterminewhichdirectiontoaddtheaccelerationto(usingthe
signfunction,whichreturns1fornumbers>0and1for<0),thencheckifweovershot.

1
2
3
4
5
6
7

vector2fdirection=vector2f(sign(targetSpeed.xcurSpeed.x),
sign(targetSpeed.ycurSpeed.y));
curSpeed+=acceleration*direction;
if(sign(targetSpeed.xcurSpeed.x)!=direction.x)
curSpeed.x=targetSpeed.x;
if(sign(targetSpeed.ycurSpeed.y)!=direction.y)
curSpeed.y=targetSpeed.y;

Itsimportanttointegratetheaccelerationintothespeedbeforemovingthecharacter,otherwise
youllintroduceaoneframelagintocharacterinput.
Whenthecharacterhitsanobstacle,itsagoodideatozerohisspeedalongthataxis.

Jumpcontrol

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%

16/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

SuperMetroid,SamusperformingtheSpaceJump(withScrewAttackpowerup)
Jumpinginaplatformgamecanbeassimpleascheckingiftheplayerisontheground(or,often,
whetherhewasonthegroundanytimeonthelastnframes),and,ifso,givingthecharacteran
initialnegativeyspeed(inphysicalterms,animpulse)andlettinggravitydotherest.
Therearefourgeneralwaysinwhichtheplayercancontrolthejump:
Impulse:seeningamessuchasSuperMarioWorldandSonictheHedgehog,thejump
preservesthemomentum(thatis,inimplementationterms,thespeed)thatthecharacterhad
beforethejump.Insomegames,thisistheonlywaytoinfluencethearcofthejumpjust
likeinreallife.Thereisnothingtoimplementhereitwillbelikethisunlessyoudo
somethingtostopit!
Aerialacceleration:thatis,retainingcontrolofhorizontalmovementwhileinmidair.
Thoughthisisphysicallyimplausible,itisaverypopularfeature,asitmakesthecharacter
muchmorecontrollable.Almosteveryplatformergamehasit,withexceptionsforgames
similartoPrinceofPersia.Generally,theairborneaccelerationisgreatlyreduced,soimpulse
isimportant,butsomegames(likeMegaMan)giveyoufullaircontrol.Thisisgenerally
implementedasmerelytweakingtheaccelerationparameterwhileyoureairborne.
Ascentcontrol:anotherphysicallyimplausibleaction,butverypopular,asitgivesyoumuch
greatercontroloverthecharacter.Thelongeryouholdthejumpbutton,thehigherthe
characterjumps.Typically,thisisimplementedbycontinuingtoaddimpulsetothecharacter
(thoughthisimpulsecanincrementallydecrease)foraslongasthebuttonisheld,or
alternativelybysuppressinggravitywhilethebuttonisheld.Atimelimitisimposed,unless
youwantthecharactertobeabletojumpinfinitely.
Multiplejumps:onceairborne,somegamesallowtheplayertojumpagain,perhapsforan
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%

17/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

unlimitednumberoftimes(asintheSpaceJumpinSuperMetroidortheflightinTalbots
Odyssey),orforalimitednumberofjumpsbeforetouchingtheground(doublejumpbeing
themostcommonchoice).Thiscanbeaccomplishedbykeepingacounterthatincreasesfor
eachjumpanddecreaseswhenyoureontheground(becarefulwhenyouupdatethis,oryou
mightresetitrightafterthefirstjump),andonlyallowingfurtherjumpsifthecounterislow
enough.Sometimes,thesecondjumpisshorterthantheinitialone.Otherrestrictionsmay
applytheSpaceJumponlytriggersifyourealreadydoingaspinjumpandjustbeganto
fall.

Animationsandleading

BlackThorne,characterdoingalonganimationbeforeshootingbackwards(Ybutton)
Inmanygames,yourcharacterwillplayananimationbeforeactuallyperformingtheactionyou
requested.However,onatwitchyactionbasedgame,thiswillfrustrateplayersDONTDO
THAT!Youshouldstillhaveleadinganimationsforthingssuchasjumpingandrunning,butif
youcareabouthowthegameresponds,makethosecosmeticonly,withtheactiontaken
immediatelyregardlessoftheanimation.

Smoothermovement
Usingintegerstorepresentthepositionofthecharactersiswise,asitmakesitfasterandstable.
However,ifyouuseintegersforeverything,youwillendupwithsomejerkymotion.Thereare
multiplesolutionstothis.Theseareafew:
Useafloatforallcomputationsandforstoringposition,andcasttointwheneveryoure
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%

18/19

19/08/2015

Theguidetoimplementing2Dplatformers|HigherOrderFun

renderingorcomputingcollisions.Fastandsimple,butitstartslosingprecisionifyoumove
toofarawayfrom(0,0).Thisisprobablynotrelevantunlessyouhaveaverylargeplayfield,
butitssomethingtokeepinmind.Ifitcomestoit,youcanuseadoubleinstead.
Useafixedpointnumberforallcomputationsandposition,andagaincasttointwhenyoure
renderingorcomputingcollisions.Lessprecisethanfloatandwithamorelimitedrange,but
theprecisionisuniformandcan,onsomehardware,befaster(notably,floatingpoint
processingisslowonmanymobilephones).
Storepositionasaninteger,butkeeparemainderstoredinafloat.Whenintegrating
position,computethedeltamovementasafloat,addtheremaindertothedeltamovement,
thenaddtheintegerpartofthisvaluetotheposition,andthefractionalparttothe
remainderfield.Onthenextframe,theremainderwillgetaddedbackin.Theadvantageof
thismethodisthatyoureusinganintegereverywhereexceptformovement,ensuringthat
youwonthavefloatingpointcomplicationselsewhere,andincreasingperformance.This
techniqueisalsoverysuitableifyouhavesomeframeworkinwhichthepositionoftheobject
hastobeaninteger,orwhereitisafloat,butthatsamepositionisuseddirectlybythe
renderingsysteminthatcase,youcanusetheframeworkprovidedfloatpositiontostore
integervaluesonly,tomakesurethattherenderingisalwaysalignedtopixels.

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%2030px%200px%3B%

19/19

Anda mungkin juga menyukai