2D Collision Detection. I wanted to make a game that would…

文章推薦指數: 80 %
投票人數:10人

The physics and movement of the characters on the screen in these games are simple and elegant. The most basic way to approach this type of 2d collision ... OpeninappHomeNotificationsListsStoriesWritePublishedinLevelUpCoding2DCollisionDetectionIwantedtomakeagamethatwouldoperateandfeellikeSuperMarioWorldoutofJavaScript.Thephysicsandmovementofthecharactersonthescreeninthesegamesaresimpleandelegant.Themostbasicwaytoapproachthistypeof2dcollisiondetectionistoutilizeaconceptknownasAxis-alignedboundingbox.Axis-alignedboundingbox,orAABB,detectsiftwonon-rotationalpolygonsareoverlappingeachother.TypicallyAABBalgorithmsrunsomethinglikethis:Wehavetwopolygons,eachwithanX(left),andaY(top)position,aswellaswidthandheightproperties.WethencompareXandYpositionsalongwithwidthandheighttoseeiftheyareoverlapping.Wetestfourconditionalstatements,ifallaretruethenweknowweareoverlapping.Letsbreakeachconditionalonit’sown.line2—A’sleftsideistotheleftofB’srightside.line3—A’srightsideistotherightofB’sleftside.line4—A’stopisaboveB’sbottom.line5—A’sbottomislowerthanB’stop.Let’splugintherealvaluesforMarioandhiscoin,representedbytheyellowandredpolygons.TheXandYpositionsofeachpolygoncomesfromthedistanceinpixelsfromtheleftandtopedgesoftheviewport.Thisalgorithmhasarobustrangeofapplications.Itcanbeusedtodetectifyourplayerisoveracollectibleitem,touchingabadguy,atthedoorattheendofthegameorjuststandingonasolidobject.GameComponentsMyprojectwasasimpletile-based2dplatformgameconsistingoftheplayerobject,a32by32pixelredsquarenamed“Cubio”,threetypesof“baddies”andthetilemapofthegame’sworld.TilesTheentiremapismadeupofjustfourtilestypes.80by80pixelsindimension,eachhasit’sownnumericalvalueandspecifiedsetsofrulesthatdeterminehowtheplayerinteractswiththemuponcollision.0:skyTheplayermovesfreelythroughthistile.1:earthIftheplayerlandsontopofthetile,theplayer’sverticalmovementstopsanditrestsontopofthetile,otherwiseitcangothroughthistileineveryotherdirection.2:crateIftheplayercollideswithanysideofthistileit’spositionstaysoutsideofthistile.3:sky_islandIftheplayerlandsontopofthetile,theplayer’sverticalmovementstopsanditrestsontopofthetile,otherwiseitcangothroughthistileineveryotherdirection.MapWithoutgoingintotoomuchdetailherethetilemapisrepresentedbyanarrayoftiletypesintheirassignedcolumnandrow,suchthatthearray:…appearsas:InteractionandBehaviorWhetheritstheskyorearth,myplayerisalwayscollidingwithatleastonetileineverysingleframesothereisnoneedtoruntheaabb()function.Mycollision_detection()functionfirstlocatesthepositionofeachcorneroftheplayer.Then,itretrievesthetypeoftilethatcorneriscollidingwith.Thenitpassesinthetile’stypeandthecorner’sxandypositionintothecollide()function.Thecollide()functionusesaswitchstatementtoselecttheappropriateblockofcodetorundependingonthetiletype.Asyoucanseetype“0”(sky)hasnoeffectandtype“2”(crate)collideswithallfoursides.IncaseyourarewonderingwhyI’vedefinedthesepointstwiceincollision_detection(),it’sbecauseeachtimeIcallcollide()ithasthepotentialtomovetheplayer.SoeverypointhastoberedefinedeachtimeafterIcallcollide().Inthesedifferenttilecollidefunctionsyoucanseetheolderpositionoftheplayeriscomparedtothetileaswell.Thisallowsyoutoestablishthedirectiontheplayerisgoing.Thefunctionneedstoknowwhatdirectiontheplayerisgoinginordertohavethecorrectresponse.Otherwiseiftheplayercollidedwiththebottomofthecratetile,it’stopisnowabovethecrate’sbottom.Thenwhenweruncollide()thecollide_top()firesfirstandplacestheplayerontopofthetile.Totheuseritwouldappearasiftheplayerwentstraightthroughthebottomofthecrateandlandedontop.Thisnegativeeffectisknownas“tunneling”.Therefore,establishingplayerdirectiongivesusabetterrepresentationofwhat’shappening.Youcanseehowthatwhenwritingabaddy_collision_detection()functionitwouldbeverysimilartothisonlywecanmodifycollide_top()tokillthebaddyandallothercollidestokilltheplayeroncontact.functionbaddyCollideTopMortal(player,bad){if(player.getBottom()>bad.getTop()&&player.getOldBottom()<=bad.getTop()){player.setBottom(bad.getTop()-0.01);player.y_velocity=-27;player.jumping=false;letdead_index=currentGame.alive_baddies.indexOf(bad);currentGame.alive_baddies.splice(dead_index,1);returntrue;}returnfalse;}functionbaddyCollideLeft(player,bad){if(player.getRight()>bad.getLeft()&&player.getOldRight()<=bad.getLeft()){player.setRight(bad.getLeft()-1);player.x_velocity=0;player_dead=true;returntrue;}returnfalse;}EfficiencywithAABB,Coins,andBaddiesOnceallofyoutiles,coinsandbaddiesareinteractingwithyouplayercorrectlyyou’llnoticethatrunningacollisiontestoneverycoinandeverybaddyateverycycleofyouengineloopisverycostlyandunnecessary.Thisiswhereyouseparatetheprocessoftestforcollisionintotwophases,broadandnarrow.BroadInthebroadphase,createanarrayofnearentities(coins,baddies).Iteratethroughthefulllistofentities,checkingtheobject’sxpositiontoseeifit’sclosetotheplayerandthenpushingthatentityintoanearlist.Thisisalotlesscostlythanrunningtheentirecollisiontestoneachentity.NarrowOnceamuchsmallerlistofnearobjectsiscreatedwetheniterateovereachtestingforcollisionwiththeaabb()functionand/orrunappropriateblocksofcode.Collisiondetectionisthemechanismthatbringsyourgametolife.Eachstepiseasytounderstandandcanbere-imaginedmanydifferentways,butonceimplementedispowerful.Happycoding!--MorefromLevelUpCodingFollowCodingtutorialsandnews.Thedeveloperhomepagegitconnected.com&&skilled.dev&&levelup.devReadmorefromLevelUpCodingRecommendedfromMediumThePragmaticProgrammersinThePragmaticProgrammersTrackingIntersectionsThePragmaticProgrammersinThePragmaticProgrammersOneFunction,MultipleBodiesThePragmaticProgrammersinThePragmaticProgrammers20.1SolveProblems,NotSymptomsThePragmaticProgrammersinThePragmaticProgrammersUsingExternalLibrariesVinitAgrawalDaggerInjectioninanAndroidLibraryThePragmaticProgrammersinThePragmaticProgrammersChapter6FunctionalThingsRicardoGutierrezDeployinganOAMClusterwithKubernetesin60MinutesThePragmaticProgrammersinThePragmaticProgrammersRunningaSubsetofScenariosAboutHelpTermsPrivacyGettheMediumappGetstartedAustinRhoads163FollowersFollowMorefromMediumArifAygünWhatisNVM,andhowtouseit?WyattGreenwayJavascript:ReadandWritebinarydatawithschreamer😱JITHINMATHEWEstimatingdepthforYOLOv5objectdetectionboundingboxesusingIntel®RealSense™DepthCamera…meghaldarjiObjectDetectionmadesimplerwithIceVision(Part-1)HelpStatusWritersBlogCareersPrivacyTermsAboutKnowable



請為這篇文章評分?