Video Game Physics Tutorial Part II: Collision Detection - Toptal
文章推薦指數: 80 %
The algorithm computes the closest points between shapes A and B, draws a vector from one point to the other, and projects the velocity on this vector to ...
DevelopersHiring?Toptalhandpickstopgamedeveloperstosuityourneeds.Top3%WhyClientsEnterpriseCommunityBlogAboutUsFollowusonLogInGotoYourProfileEngineeringAllBlogsIconChevronIconCloseSearchFilterbyAllEngineeringDesignFinanceProjectsProductToptalInsightsViewallresultsEngineeringDesignFinanceProjectsProductToptalInsightsTechnology21minutereadVideoGamePhysicsTutorial-PartII:CollisionDetectionforSolidObjectsInPartIofthisthree-partseriesongamephysics,weexploredrigidbodiesandtheirmotions.Inthatdiscussion,however,objectsdidnotinteractwitheachother.Withoutsomeadditionalwork,thesimulatedrigidbodiescangorightthrougheachother.
InPartII,wewillcoverthecollisiondetectionstep,whichconsistsoffindingpairsofbodiesthatarecollidingamongapossiblylargenumberofbodiesscatteredarounda2Dor3Dworld.
AuthorAuthorNilsonSoutoNilson(dualBCS/BScTech)beenaniOSdevand2D/3Dartistfor8+years,focusingonphysicsandvehiclesimulations,games,andgraphics.
SHARESHAREThisisPartIIofourthree-partseriesonvideogamephysics.Fortherestofthisseries,see:
PartI:AnIntroductiontoRigidBodyDynamics
PartIII:ConstrainedRigidBodySimulation
InPartIofthisseries,weexploredrigidbodiesandtheirmotions.Inthatdiscussion,however,objectsdidnotinteractwitheachother.Withoutsomeadditionalwork,thesimulatedrigidbodiescangorightthrougheachother,or“interpenetrate”,whichisundesirableinthemajorityofcases.
Inordertomorerealisticallysimulatethebehaviorofsolidobjects,wehavetocheckiftheycollidewitheachothereverytimetheymove,andiftheydo,wehavetodosomethingaboutit,suchasapplyingforcesthatchangetheirvelocities,sothattheywillmoveintheoppositedirection.Thisiswhereunderstandingcollisionphysicsisparticularlyimportantforgamedevelopers.
InPartII,wewillcoverthecollisiondetectionstep,whichconsistsoffindingpairsofbodiesthatarecollidingamongapossiblylargenumberofbodiesscatteredarounda2Dor3Dworld.Inthenext,andfinal,installment,we’lltalkmoreabout“solving”thesecollisionstoeliminateinterpenetrations.
Forareviewofthelinearalgebraconceptsreferredtointhisarticle,youcanrefertothelinearalgebracrashcourseinPartI.
CollisionPhysicsinVideoGames
Inthecontextofrigidbodysimulations,acollisionhappenswhentheshapesoftworigidbodiesareintersecting,orwhenthedistancebetweentheseshapesfallsbelowasmalltolerance.
Ifwehavenbodiesinoursimulation,thecomputationalcomplexityofdetectingcollisionswithpairwisetestsisO(n2),anumberthatmakescomputerscientistscringe.Thenumberofpairwisetestsincreasesquadraticallywiththenumberofbodies,anddeterminingiftwoshapes,inarbitrarypositionsandorientations,arecollidingisalreadynotcheap.Inordertooptimizethecollisiondetectionprocess,wegenerallysplititintwophases:broadphaseandnarrowphase.
Thebroadphaseisresponsibleforfindingpairsofrigidbodiesthatarepotentiallycolliding,andexcludingpairsthatarecertainlynotcolliding,fromamongstthewholesetofbodiesthatareinthesimulation.ThisstepmustbeabletoscalereallywellwiththenumberofrigidbodiestomakesurewestaywellundertheO(n2)timecomplexity.Toachievethat,thisphasegenerallyusesspacepartitioningcoupledwithboundingvolumesthatestablishanupperboundforcollision.
Thenarrowphaseoperatesonthepairsofrigidbodiesfoundbythebroadphasethatmightbecolliding.Itisarefinementstepwherewedetermineifthecollisionsareactuallyhappening,andforeachcollisionthatisfound,wecomputethecontactpointsthatwillbeusedtosolvethecollisionslater.
Inthenextsectionswe’lltalkaboutsomealgorithmsthatcanbeusedinthebroadphaseandnarrowphase.
BroadPhase
Inthebroadphaseofcollisionphysicsforvideogamesweneedtoidentifywhichpairsofrigidbodiesmightbecolliding.Thesebodiesmighthavecomplexshapeslikepolygonsandpolyhedrons,andwhatwecandotoacceleratethisistouseasimplershapetoencompasstheobject.Iftheseboundingvolumesdonotintersect,thentheactualshapesalsodonotintersect.Iftheyintersect,thentheactualshapesmightintersect.
Somepopulartypesofboundingvolumesareorientedboundingboxes(OBB),circlesin2D,andspheresin3D.Let’slookatoneofthesimplestboundingvolumes:axis-alignedboundingboxes(AABB).
AABBsgetalotoflovefromphysicsprogrammersbecausetheyaresimpleandoffergoodtradeoffs.A2-dimensionalAABBmayberepresentedbyastructlikethisintheClanguage:
typedefstruct{
floatx;
floaty;
}Vector2;
typedefstruct{
Vector2min;
Vector2max;
}AABB;
Theminfieldrepresentsthelocationofthelowerleftcorneroftheboxandthemaxfieldrepresentsthetoprightcorner.
TotestiftwoAABBsintersect,weonlyhavetofindoutiftheirprojectionsintersectonallofthecoordinateaxes:
BOOLTestAABBOverlap(AABB*a,AABB*b)
{
floatd1x=b->min.x-a->max.x;
floatd1y=b->min.y-a->max.y;
floatd2x=a->min.x-b->max.x;
floatd2y=a->min.y-b->max.y;
if(d1x>0.0f||d1y>0.0f)
returnFALSE;
if(d2x>0.0f||d2y>0.0f)
returnFALSE;
returnTRUE;
}
Thiscodehasthesamelogicoftheb2TestOverlapfunctionfromtheBox2Dengine(version2.3.0).ItcalculatesthedifferencebetweentheminandmaxofbothAABBs,inbothaxes,inbothorders.Ifanyofthesevaluesisgreaterthanzero,theAABBsdon’tintersect.
EventhoughanAABBoverlaptestischeap,itwon’thelpmuchifwestilldopairwisetestsforeverypossiblepairsincewestillhavetheundesirableO(n2)timecomplexity.TominimizethenumberofAABBoverlaptestswecanusesomekindofspacepartitioning,whichwhichworksonthesameprinciplesasdatabaseindicesthatspeedupqueries.(Geographicaldatabases,suchasPostGIS,actuallyusesimilardatastructuresandalgorithmsfortheirspatialindexes.)Inthiscase,though,theAABBswillbemovingaroundconstantly,sogenerally,wemustrecreateindicesaftereverystepofthesimulation.
Thereareplentyofspacepartitioningalgorithmsanddatastructuresthatcanbeusedforthis,suchasuniformgrids,quadtreesin2D,octreesin3D,andspatialhashing.Letustakeacloserlookattwopopularspatialpartitioningalgorithms:sortandsweep,andboundingvolumehierarchies(BVH).
TheSortandSweepAlgorithm
Thesortandsweepmethod(alternativelyknownassweepandprune)isoneofthefavoritechoicesamongphysicsprogrammersforuseinrigidbodysimulation.TheBulletPhysicsengine,forexample,hasanimplementationofthismethodinthebtAxisSweep3class.
TheprojectionofoneAABBontoasinglecoordinateaxisisessentiallyaninterval[b,e](thatis,beginningandend).Inoursimulation,we’llhavemanyrigidbodies,andthus,manyAABBs,andthatmeansmanyintervals.Wewanttofindoutwhichintervalsareintersecting.
Inthesortandsweepalgorithm,weinsertallbandevaluesinasinglelistandsortitascendingbytheirscalarvalues.Thenwesweeportraversethelist.Wheneverabvalueisencountered,itscorrespondingintervalisstoredinaseparatelistofactiveintervals,andwheneveranevalueisencountered,itscorrespondingintervalisremovedfromthelistofactiveintervals.Atanymoment,alltheactiveintervalsareintersecting.(CheckoutDavidBaraff’sPh.DThesis,p.52fordetails.Isuggestusingthisonlinetooltoviewthepostscriptfile.)Thelistofintervalscanbereusedoneachstepofthesimulation,wherewecanefficientlyre-sortthislistusinginsertionsort,whichisgoodatsortingnearly-sortedlists.
Intwoandthreedimensions,runningthesortandsweep,asdescribedabove,overasinglecoordinateaxiswillreducethenumberofdirectAABBintersectionteststhatmustbeperformed,butthepayoffmaybebetteroveronecoordinateaxisthananother.Therefore,moresophisticatedvariationsofthesortandsweepalgorithmareimplemented.InhisbookReal-TimeCollisionDetection(page336),ChristerEricsonpresentsanefficientvariationwherehestoresallAABBsinasinglearray,andforeachrunofthesortandsweep,onecoordinateaxisischosenandthearrayissortedbytheminvalueoftheAABBsinthechosenaxis,usingquicksort.Then,thearrayistraversedandAABBoverlaptestsareperformed.Todeterminethenextaxisthatshouldbeusedforsorting,thevarianceofthecenteroftheAABBsiscomputed,andtheaxiswithgreatervarianceischosenforthenextstep.
DynamicBoundingVolumeTrees
Anotherusefulspatialpartitioningmethodisthedynamicboundingvolumetree,alsoknownasDbvt.Thisisatypeofboundingvolumehierarchy.
TheDbvtisabinarytreeinwhicheachnodehasanAABBthatboundsalltheAABBsofitschildren.TheAABBsoftherigidbodiesthemselvesarelocatedintheleafnodes.Typically,aDbvtis“queried”bygivingtheAABBforwhichwewouldliketodetectintersections.ThisoperationisefficientbecausethechildrenofnodesthatdonotintersectthequeriedAABBdonotneedtobetestedforoverlap.Assuch,anAABBcollisionquerystartsfromtheroot,andcontinuesrecursivelythroughthetreeonlyforAABBnodesthatintersectwiththequeriedAABB.Thetreecanbebalancedthroughtreerotations,asinanAVLtree.
Box2DhasasophisticatedimplementationofDbvtintheb2DynamicTreeclass.Theb2BroadPhaseclassisresponsibleforperformingthebroadphase,anditusesaninstanceofb2DynamicTreetoperformAABBqueries.
NarrowPhase
Afterthebroadphaseofvideogamecollisionphysics,wehaveasetofpairsofrigidbodiesthatarepotentiallycolliding.Thus,foreachpair,giventheshape,positionandorientationofbothbodies,weneedtofindoutiftheyare,infact,colliding;iftheyareintersectingoriftheirdistancefallsunderasmalltolerancevalue.Wealsoneedtoknowwhatpointsofcontactarebetweenthecollidingbodies,sincethisisneededtoresolvethecollisionslater.
ConvexandConcaveShapes
Asavideogamephysicsgeneralrule,itisnottrivialtodetermineiftwoarbitraryshapesareintersecting,ortocomputethedistancebetweenthem.However,onepropertythatisofcriticalimportanceindeterminingjusthowharditis,istheconvexityoftheshape.Shapescanbeeitherconvexorconcaveandconcaveshapesarehardertoworkwith,soweneedsomestrategiestodealwiththem.
Inaconvexshape,alinesegmentbetweenanytwopointswithintheshapealwaysfallscompletelyinsidetheshape.Howeverforaconcave(or“non-convex”)shape,thesameisnottrueforallpossiblelinesegmentsconnectingpointsintheshape.Ifyoucanfindatleastonelinesegmentthatfallsoutsideoftheshapeatall,thentheshapeisconcave.
Computationally,itisdesirablethatallshapesareconvexinasimulation,sincewehavealotofpowerfuldistanceandintersectiontestalgorithmsthatworkwithconvexshapes.Notallobjectswillbeconvexthough,andusuallyweworkaroundthemintwoways:convexhullandconvexdecomposition.
Theconvexhullofashapeisthesmallestconvexshapethatfullycontainsit.Foraconcavepolygonintwodimensions,itwouldbelikehammeringanailoneachvertexandwrappingarubberbandaroundallnails.Tocalculatetheconvexhullforapolygonorpolyhedron,ormoregenerally,forasetofpoints,agoodalgorithmtouseisthequickhullalgorithm,whichhasanaveragetimecomplexityofO(nlogn).
Obviously,ifweuseaconvexhulltorepresentaconcaveobject,itwillloseitsconcaveproperties.Undesirablebehavior,suchas“ghost”collisionsmaybecomeapparent,sincetheobjectwillstillhaveaconcavegraphicalrepresentation.Forexample,acarusuallyhasaconcaveshape,andifweuseaconvexhulltorepresentitphysicallyandthenputaboxonit,theboxmightappeartobefloatinginthespaceabove.
Ingeneral,convexhullsareoftengoodenoughtorepresentconcaveobjects,eitherbecausetheunrealisticcollisionsarenotverynoticeable,ortheirconcavepropertiesarenotessentialforwhateverisbeingsimulated.Insomecases,though,wemightwanttohavetheconcaveobjectbehavelikeaconcaveshapephysically.Forexample,ifweuseaconvexhulltorepresentabowlphysically,wewon’tbeabletoputanythinginsideofit.Objectswilljustfloatontopofit.Inthiscase,wecanuseaconvexdecompositionoftheconcaveshape.
Convexdecompositionalgorithmsreceiveaconcaveshapeandreturnasetofconvexshapeswhoseunionisidenticaltotheoriginalconcaveshape.Someconcaveshapescanonlyberepresentedbyalargenumberofconvexshapes,andthesemightbecomeprohibitivelycostlytocomputeanduse.However,anapproximationisoftengoodenough,andso,algorithmssuchasV-HACDproduceasmallsetofconvexpolyhedronsoutofaconcavepolyhedron.
Inmanycollisonsphysicscases,though,theconvexdecompositioncanbemadebyhand,byanartist.Thiseliminatestheneedtotaxperformancewithdecompositionalgorithms.Sinceperformanceisoneofthemostimportantaspectsinreal-timesimulations,it’sgenerallyagoodideatocreateverysimplephysicalrepresentationsforcomplexgraphicobjects.Theimagebelowshowsonepossibleconvexdecompositionofa2Dcarusingnineconvexshapes.
TestingforIntersections-TheSeparatingAxisTheorem
Theseparatingaxistheorem(SAT)statesthattwoconvexshapesarenotintersectingifandonlyifthereexistsatleastoneaxiswheretheorthogonalprojectionsoftheshapesonthisaxisdonotintersect.
It’susuallymorevisuallyintuitivetofindalinein2Doraplanein3Dthatseparatesthetwoshapes,though,whichiseffectivelythesameprinciple.Avectororthogonaltothelinein2D,orthenormalvectoroftheplanein3D,canbeusedasthe“separatingaxis”.
Gamephysicsengineshaveanumberofdifferentclassesofshapes,suchascircles(spheresin3D),edges(asinglelinesegment),andconvexpolygons(polyhedronsin3D).Foreachpairofshapetype,theyhaveaspecificcollisiondetectionalgorithm.Thesimplestofthemisprobablythecircle-circlealgorithm:
typedefstruct{
floatcenterX;
floatcenterY;
floatradius;
}Circle;
boolCollideCircles(Circle*cA,Circle*cB){
floatx=cA->centerX-cB->centerX;
floaty=cA->centerY-cB->centerY;
floatcenterDistanceSq=x*x+y*y;//squareddistance
floatradius=cA->radius+cB->radius;
floatradiusSq=radius*radius;
returncenterDistanceSq<=radiusSq;
}
EventhoughtheSATappliestocircles,it’smuchsimplertojustcheckifthedistancebetweentheircentersissmallerthanthesumoftheirradii.Forthatreason,theSATisusedinthecollisiondetectionalgorithmforspecificpairsofshapeclasses,suchasconvexpolygonagainstconvexpolygon(orpolyhedronsin3D).
Foranypairofshapes,thereareaninfinitenumberofaxeswecantestforseparation.Thus,determiningwhichaxistotestfirstiscrucialforanefficientSATimplementation.Fortunately,whentestingifapairofconvexpolygonscollide,wecanusetheedgenormalsaspotentialseparatingaxes.Thenormalvectornofanedgeisperpendiculartotheedgevector,andpointsoutsidethepolygon.Foreachedgeofeachpolygon,wejustneedtofindoutifalltheverticesoftheotherpolygonareinfrontoftheedge.
Ifanytestpasses–thatis,if,foranyedge,allverticesoftheotherpolygonareinfrontofit–thenthepolygonsdonotintersect.Linearalgebraprovidesaneasyformulaforthistest:givenanedgeonthefirstshapewithverticesaandbandavertexvontheothershape,if(v-a)·nisgreaterthanzero,thenthevertexisinfrontoftheedge.
Forpolyhedrons,wecanusethefacenormalsandalsothecrossproductofalledgecombinationsfromeachshape.Thatsoundslikealotofthingstotest;however,tospeedthingsup,wecancachethelastseparatingaxisweusedandtryusingitagaininthenextstepsofthesimulation.Ifthecachedseparatingaxisdoesnotseparatetheshapesanymore,wecansearchforanewaxisstartingfromfacesoredgesthatareadjacenttothepreviousfaceoredge.Thatworksbecausethebodiesoftendon’tmoveorrotatemuchbetweensteps.
Box2DusesSATtotestiftwoconvexpolygonsareintersectinginitspolygon-polygoncollisiondetectionalgorithminb2CollidePolygon.cpp.
ComputingDistance-TheGilbert-Johnson-KeerthiAlgorithm
Inmanycollisionsphysicscases,wewanttoconsiderobjectstobecollidingnotonlyiftheyareactuallyintersecting,butalsoiftheyareveryclosetoeachother,whichrequiresustoknowthedistancebetweenthem.TheGilbert-Johnson-Keerthi(GJK)algorithmcomputesthedistancebetweentwoconvexshapesandalsotheirclosestpoints.Itisanelegantalgorithmthatworkswithanimplicitrepresentationofconvexshapesthroughsupportfunctions,Minkowskisums,andsimplexes,asexplainedbelow.
SupportFunctions
AsupportfunctionsA(d)returnsapointontheboundaryoftheshapeAthathasthehighestprojectiononthevectord.Mathematically,ithasthehighestdotproductwithd.Thisiscalledasupportpoint,andthisoperationisalsoknownassupportmapping.Geometrically,thispointisthefarthestpointontheshapeinthedirectionofd.
Findingasupportpointonapolygonisrelativelyeasy.Forasupportpointforvectord,youjusthavetoloopthroughitsverticesandfindtheonewhichhasthehighestdotproductwithd,likethis:
Vector2GetSupport(Vector2*vertices,intcount,Vector2d){
floathighest=-FLT_MAX;
Vector2support=(Vector2){0,0};
for(inti=0;i
延伸文章資訊
- 1Collision Detection: Algorithms and Applications
We present an e cient and accurate algorithm for collision detection between general polygonal mo...
- 2Efficient Algorithms for Two-Phase Collision Detection
This article describes practical collision detection algorithms for robot motion planning. Attent...
- 3Collision detection - Wikipedia
Collision detection is the computational problem of detecting the intersection of two or ... Coll...
- 4Collision Detection - Jeff Thompson
This book explains the algorithms behind those collisions using basic shapes like circles, rectan...
- 52D collision detection - Game development - MDN Web Docs
Algorithms to detect collision in 2D games depend on the type of shapes that can collide (e.g. Re...