I reallymeanapproximatecollisionsonWealsoconsiderthisroadbe a completephysicsenginebecausewe'renotgoingtobeconsideringtherotationorangularvelocityoffthecircularobjects.
I justaddedmorefeatures, andwe'llseethoseoverthecomingvideos.
I havetouchedonphysicsonquite a fewvideosalready, particularlyasteroidsgame.
TheFlappyBirdsgameontodecodeityourselfworms.
Siri's.
So I'm notgoingtogothroughallofthebasicsoffKinnahMaticsagain, However, mostofourobjectsherearegoingtobe a circleon a circleisrepresentedby a pointwhichwillcall P X on P Y.
Cyclesalsohave a radius.
But I'm alsogoingtoaddtomycircleobjectthevelocityvector V X on D V y.
Andforcompleteness.
I'm alsogoingtoaddanaccelerationfactor, a x and A y.
Andifyouremember, thisis a vectoroffpersofffloats, sothateachpercontainsan X and Y coordinate, anditwilllinkallofthecoordinatestogetherwithstraightlines.
Soifwewantsomethingthatrepresents a circle, we'vegottobuildup a circleoutofstraightlinesegments.
Weonlyneedonemodelof a circlebecausewellcreatedas a unitcircleonwillscaleitaccordingly.
So I'm goingtostartbyadding a singlepointtothecenterofthecircle.
Eachcircleisgoingtoconsistof 20 segments, and I'm goingtouseouroldfriendscosignandsigntocreatethe X and Y coordinatesoffthepointsthatlieonthecircumferenceofthecirclearounditsmiddlepoint.
Ofcourse, on, becausemodelcircleis a vector, I cansimplyjustpushbackthenewgroupsofcoordinates.
Ourballsimulationwillcontainmanyballs.
So I'm goingtocreate a vectortostallthemallin, And I'm alsogoingtoadd a utilityfunctiontomakeitmoreconvenienttoaddballstothisvector.
Sohere I specifythelocationon I setthevelocityandaccelerationvectorstozerosoit's notgoingtomove.
Pythagorassitsthereon I amgoingto, but I'm goingtomodifyitslightlytoremovethesquarerootbecausethesquarerootcanbequitecostlytocomputeandwe'llbedoing a lotofthem.
Sonormallywewoulddoitlikethis.
Wewouldtakethedifferencebetweenthetwo X coordinatesandsquarethemaddedtothedistancebetweenthetwo.
Somylambdafunctionissimplygoingtoreturn a Booleanastowhetherthatconditionistrue.
Nowwecanaddanotherclausetoourcollisiondetection.
Wecanchecktoseeifthecirclesareinfactinconflictwitheachother, sowe'llhavethe X coordinateofftheballwe'recurrentlyoperatingupanditsradiusonthesameforthetarget.
Ifthisconditionistrue, thenwe'vegot a collision.
Eventhough I'm makingattempttooptimizethecodenow, I don't consideritthemostimportantpriority.
Andinfactsomeoftheprosouttherewillnotice.
Actually, there's a lotmorescopeforoptimizationinthisprogram, but I wanttokeepitsimplesopeoplecanfollowalong.
Pythagorasistheresquarerootofthedifferencebetweenthe X's and Y's ofbothballs.
Calculatingtheoverlapisthesameasourlambdafunctionbeforewhatwewanttodosomething a littlebitdifferentthistimesowecanseeitasit's thedistancebetweenthetwopoints.
Subtractingboththeradiusisofeachball.
However, weonlywanthalftheoverlapbecausethat's howmuchwe'regoingtodisplaceeachball.
So I put a multipliedbyhalfatthefronttoresolvethestaticcollision.
I knowit's nolongerthefashiontousepointersanymore, orso I'm told.
But I quitelikethefactthatyougettofunctionsforthepriceofoneexpertpointer.
Firstly, itpointstosomethinginteresting, andsecondly, ifit's settonopointsthatweknowthatthepointisnovalidand I likethefactthatwecanleveragethevalidityof a pointthat's partoftheprogram.
Ifit's notinyourpointer, we'rejustgoingtodirectlysettothePXand P Y valuestothemousecoordinates.
Let's take a look.
Sonow I shouldbeabletopickup a ballwiththeleftmousebutton, andif I pushitintotheotherballonthescreen, wecanseetheydon't overlap, andtheydowhattheycantoavoidoverlapping.
I'm justgoingtoaddtotheaddressesofthoseballstothisvector, andthismeansoncewe'veworkedoutwhereallthecollisionshaveoccurred, wecanthendealwiththemwith a reasonablyaccurateapproximationtophysics.
Byhaving a factorthatcontainsjustthecollidingobjects, wecanuse a fulllooptoeautomaticallyschoolthroughthesecollidingpearsandupdatethemwithapproximationstophysics.
Accordingly.
We'llcomebacktothatin a minute, Butfirst I'd liketodrawwhichballsareincontactwitheachotherandbecausewehave a vectorofcollisions, Thisisverysimpletowejustscrollthroughthevectoron.
Wedraw a linefromthecenteroffoneofthecollidingpairstothecenteroftheother, and I'm goingtodrawitas a redline.
I don't needtoemptythespecterbecausewhenthisfunctionreturns, thevectorgoesoutofscopeanditwillbedestroyed.
Let's take a look.
Soif I pickup a ballandforceitintocollisionwithsomethingelse, wecanseethereis a collisionlineindicator.
Handlingthedynamicresolutionis a littlebitmoretricky, solet's justhave a lookatwhatcomesintoplayduringthiscollision.
Firstly, let's assumethatthisballontheleftismovingwith a velocityinthatdirection.
Onthisballontherightismovingwith a velocityinthisdirection.
Weknowthattheballsdon't overlapon.
Wecandeterminetousefulcharacteristics.
Firstly, ifwedraw a linebetweenthetwocenterpointsandfindthenormaltothatline a a line 90 degreestoit, tryanddrawit a straightas I canhere.
Actually, it's 90 degreesthistown, gentlelinethatwe'vejustdonebecauseit's a tangenttothecircumferenceofthecircleeffectivelyrepresents a solidobjectfor a balltobounceoff.
I'lljustlabelthatonetongentleontheline, normaltothetangentundersimplygoingtoretainthenamenormalNowin a perfectworld, andassumingthatthetargetballwasaddressed, ithadnoinitialvelocity.
Conservationofmomentumsuggeststhatthemomentumofthiswholesystembeforethecollisionshouldbethesameasthemomentumafterthecollisionorwhat's nicein R two d CircleScenariois, wereallyonlyhavetoconsidermomentuminonedimension, andwecanusethemomentumequationstoinfluence a normalresponse.
Asalways, Wikipediais a greatresourceforallthingsgamesprogramming, anditdoeshave a greatarticleonelasticcollisions, anditshowsusheretheequationsthatwewillneedtouseinordertocalculatethevelocitiesafter a collision.
Assumingthecollisioniselastic, ofcourse.
Nowthisbeingtheoneloancodedchannel, I wouldusuallyliketotryandderivetheseequationsfromfirstprinciples, andso I did.
But I'vedecidednottoincludeitinthevideosimplybecauseitisquite a lot.
It's quitedemanding.
There's a lottodo, soifyoufancythechallenge, youcanhave a goatdoingthat.
Now, intheinterestoffulldisclosure, I willsaythatthisapproachseems a littlebitlaboriousandinfact, ifwegobacktothesameWikipediaarticle, itgivesustwofunctionsthatcalculateexactlythevelocityvectorsweneedforthescenariothatwe'vegot.
WhatitboilsdowntoisthattheWikipediaversionis a cleverlydeducedversionofthesamemathswheretheylookedatalloftheredundanciesandgotridofthemonthey'vebrokenitdownintojustitspurest, mostsimpleform.