mary rose cook

2D collision detection in Pistol Slut

For the last six months, I’ve been writing Pistol Slut, a 2D shoot-em-up in JavaScript. In this article, I’ll talk about how I solved some of the nastier problems with detecting collisions between 2D objects, specifically: bullets, grenades, exploding barrels, buildings and people.

You might find it helpful to play Pistol Slut before you read on, so you have a context for the things I talk about.

I will not be talking about per-pixel collision detection. And I will only be talking about objects whose shapes can be roughly approximated to a rectangle.

Most of the examples in this article will be conducted in pseudo-code. If you want to see the code I actually used, go and look at the repository for Pistol Slut. Both it, and the framework it is based on, The Render Engine, are open source under the MIT license. This means you can take the code and use it in any project, commercial or non-commercial, open source or not.

This article will begin with the general approach to collision detection. It will then go into special cases that solve some of the trickier problems.

Grids

Imagine the whole game world split up by a grid. If two objects are in the same square of the grid, we assume they are colliding, like these two red squares.

Whereas, these two red squares are not colliding:

So, to detect whether a particular object is colliding with another one in our simple little world, we can use this code:

What if the world looks like this?

Uh-oh.

An object might exist in more than one grid square. How about we get the coordinates of all four corners of each object and add the object to the grid square containers into which the coordinates of those corners fall? No, that’s not going to fly, either, because the world might look like this:

There are two solutions. Solution one, use bounding boxes, the subject of the next section. But we don’t really want to do that, because the grid is supposed to be a super-quick triage that dramatically cuts down the number of collisions we have to test further. Solution two, assume that an object will never be bigger than a grid square and, therefore, we can just add it to the grid square container into which its top left corner falls, and the containers of the eight surrounding squares. To make this happen, we can modify the second block in the previous code, giving us:

One last thing: what happens if an object moves? It might have moved to a new grid square. It’s no big deal:

Bounding boxes

We can now get a list of all the objects that a particular object is colliding with. But that’s kind of lies, isn’t it? Though the two red squares in the first diagram are occupying the same grid square, they aren’t actually colliding. Grid square co-habitation is only the first step. The next is to find out whether an object is actually overlapping another object, like these two love-birds:

We do this with bounding boxes. A bounding box is a square that is as tight a fit as possible around the actual boundaries of an object. A bounding box is defined by the x and y coordinates of its top left corner and the x and y coordinates of its bottom right corner. If two objects’ bounding boxes overlap, those two objects are colliding. To calculate if two bounding boxes overlap, we run four tests that would confirm the boxes *don’t* overlap. If all four tests come back false, the boxes are overlapping:

To get all the objects that a particular object is colliding with:

Putting it all together

The object’s reaction may depend on what type of object it has collided with. Its decision about whether it wants to hear about more objects in its grid square in this tick might depend on whether its reaction involved it being destroyed. If it is destroyed, it will probably remove itself permanently from the pool of objects in the grid.

Special cases

This is the tougher stuff. I’ll talk about how to deal with fast-moving objects, objects that can stand on top of others, objects that can push others and objects that bounce.

The root cause of most of the difficulties is the fact that objects can move several pixels per tick. Thus, you do not always hear about collisions until after one object is well inside another. Thus, it’s sometimes hard to tell at what coordinates the impact occurred. I’ll take some objects from Pistol Slut, explain the difficulties with each object, and the solutions.

Bullets

Problem one: in a tick, bullets can pass right through objects they should be colliding with. Solution: make sure they can’t ever move at a pixel speed higher than your narrowest object. You could do this by taking care to build objects that aren’t too narrow, or put a speed limit on bullets that is based on the width of your narrowest object.

Problem two: it’s hard to tell at what coordinates a bullet entered a dustbin, which makes it difficult to show the point of impact with a shower of sparks. Solution: extrapolate back through time. I have no idea what this technique is really called.

Here is a red dustbin with a red bullet being shot at it. It passes through positions A, B and C in that order.

Unfortunately, ticks only occur when the bullet is at positions A and C. Therefore, with the system outlined above, the bullet won’t know about a collision until it reaches position C. That will be fine for destroying the bullet to represent the fact that it has hit the dustbin, but it won’t be so great for doing the beautiful shower of sparks. If we drew those sparks at point C, the location of the bullet when we detected the collision, they would look like this:

Lame.

We need to find position B. That way, the sparks will originate from the point of impact. As a bonus, I will show you how to make the sparks go in the right direction.

For the first part, draw an imaginary green line between position C and position A. That is, a line between where the bullet is now and where the bullet was in the previous tick. Then, draw four more imaginary purple lines, one along each side of the bounding box of the dustbin.

The move is to find out which bounding box line the C to A line intersects, and where. Here are two JavaScript functions; the first tells you if a line between p1 and p2 and a line between p3 and p4 are intersecting and the second tells you where.

So, with the power of maths in our hands, we can now figure out where position B is:

And, thus, emit the shower of sparks from that point.

But in which rough direction should the sparks go? Ack. Start crying: here comes some more maths.

reverseAngle() is the key function, here. It gets the normal to the side of the dustbin that the bullet hit. That is, it gets the outward-facing line that is perpendicular. It gets the angle between the normal and the bullet’s vector and then spins that angle around to adjust it to the direction appropriate for the side that was hit. The result is the angle the sparks should go along.

Grenades

Problem one: grenades bounce. Solution: use the code from the Bullets section to get the point of impact of the grenade and then reflect the angle of impact and send the grenade off in this new direction. And maybe reduce the grenade’s velocity a little to account for friction and the fact that grenades aren’t exactly like super balls when it comes to bouncing. Easy.

Problem two: solution one was a bit of a lie. The reflect direction stuff we used for bullets will still work great with grenades, but the stuff with using the grenade’s current and previous positions to get its trajectory and, thus, where it hit the dustbin, can be problematic. It’ll work most of the time, but not all. I’ll explain why.

When we drew the imaginary line between the current and previous positions of the bullet, we drew it between the top right hand corners of the two positions. This is fine, because the bullet actually IS only a single point. It’s drawn as a single pixel. But grenades are bigger than that. So, something like this might happen:

The first time we hear about a collision with the red dustbin will be when the red grenade is at position A. The next tick will find the grenade at position C. But there’s no position B. Why? Because we will draw a line between the top lefts of the grenade at positions A and C, and that line will not intersect with any of the sides of the red dustbin. Thus, we will not get a point of impact and, thus, we won’t know where to bounce the grenade from.

Why not draw lines between every corner of the previous and next positions? That is, top left to top left, top right to top right and so forth. Good thinking, clever-clogs. But what about this scenario?

Do you see? Though the red grenade is colliding with the red dustbin at both positions A and C, a line drawn from the top left of position A to the top left of position C would not intersect the edge of the dustbin. The same goes for a line from top right to top right, bottom left to bottom left and bottom right to bottom right.

The solution has two cases. In the first case, at a particular tick, the red grenade is intersecting the side of the red dustbin:

In this case, the code to get the angle to bounce the grenade is straightforward:

To determine whether a line intersects a box, make a rectangle of the line and then see if that rectangle overlaps the box rectangle. To make a rectangle from a horizontal or vertical line between p1 and p2:

In the second case, the red grenade is already fully inside the dustbin:

To deal with this, we use a technique called sweeping. The idea is to move the grenade back along its trajectory in small increments, testing at each position to see if it is overlapping any of the sides of the dustbin. Like this:

The initial collision is detected when the grenade is at position A. We then sweep its position back incrementally to positions B, C and D, testing to see if it collides with any of the edges of the red dustbin. We finally get a hit at position E.

To handle both this case and the previous case, we can write this code:

People

What is special about people? They can bump into and stand on top of things. To handle these scenarios, we can write this code:

And to figure out whether the girl is falling or rising or walking through the dustbin, we can write this code:

Exploding barrels

Exploding barrels are not so notable for their explodeyness as for the fact that they can be pushed. Using the code we are already using for the girl, we can handle this:

Artificial intelligence

That’s it for the collision detection in Pistol Slut. Well done. My next article will be about artificial intelligence with state machines.

treating bipolar with abilify and zyprexa

stanozolol dosage connecticut imitrex and zoloft generic plavix and recall grande librairie sp cialis e tunisie substitute for soma

hyzaar allergy

ativan dosage breast augmentation canda acid and calcium carbonate inmediatez tentativa actos preparatorios cephalexin fir strep

shower after breast augmentation

deca winstrol lexapro length of withdrawal bergen county breast augmentation file viewtopic t 144 viagra night sweats and lexapro

premature ejaculation zoloft

ephedrine-extract zoloft synthroid menopause zopiclone prozac can requip cause feet to swell viagra and light sensitivity

dilantin heart medication

diazepam dosage catholic and clomid ontario breast augmentation hgh norway a to z zocor

singulair aerator motor

increase testerone augmentin stealing sun pharma generic plavix effexor withdrawal mayo clinic quit smoking zyban

calcium coral okinawas

how to take ultram and tramadol zoloft micrograms plaintiff's attorney avandia 1871 accutane guild paternity rights guild legal overdose on aleve

brian soma

stanozolol cycle kodak vr35 point and shoot nizoral swish and swallow lamictal and manufacturer tramadol vs vikaden

seagram's green tea ginger ale

buy tramadol tramadol interference with opioid drug testing consumer reports january 2006 zoloft effexor valtrex tramadol erectile dysfunction ed tercel trouble shoot

poppy z brite nudes

ambien for sleep tramadol 50mg dosage evista power candida esophagitis diflucan lisinopril to treat diabetes

natural breast enhancement program actives

ativan lorazepam side effects of dog takin cephalexin bandolino shoot motrin comprimidos cozaar is it safe

hcpcs for cardizem

buy methylphenidate online levaquin long term side effects is nexium better than protonix cute young first phot shoot steve nissen avandia threatened

sar methods chemistry analog tricor

get vicodin smoking on prozac what is in rogaine tylenol and motrin interaction lexapro and sexual side affects

sublingual melatonin retail

buy atarax soma fm streams trouble shoot air conditioner clomid clomiphene near breast cancer risk aleve pets dosage

cialis in the system

cialis is tadalifil diflucan in treatment of valley fever brites disease calan for headaches viagra se games

celebrex drug side effects

buy oxycontin james meister exelon levaquin 500mg and std carl edwards 99 2008 claritin car hoodia pomegran real

hair transplants propecia

dexedrine cost are hives common with synthroid green tea drink neurontin side effects dosage answers to zyban lab

aiya matcha green tea

ephedrine-doseage prednisone dogs shrink tumor clomid iui rate success cla dia almeida sandisk shoot and storage card

breast augmentation centers in mo

get percocet clomid increase cervical fluids mycoplasma pneumonia with cipro lamictal withdrawal symptoms side effects steroid viagra

minnesota green tea weight loss

buy xanax online indications for neurontin archery bow shoots jackson mn atarax 75mg lamisil cream and herpes

aleve gout

clonazepam dosages ruby shoots oswald video hair loss neurontin peach green tea concentrate free sample of cytotec

cla bucholz

fexofenadine and pseudoephedrine tricor fenofibrate tablets injuries caused by accutane inderal red face benefits from effexor

topamax and menopause

get oxycontin hyzaar 100 25 melatonin megadose adalat nasibov how to make green tea extract

actos dosage

benzphetamine hydrochloride green tea adrenal fatigue treating migraines with prozac crestor show results ashwagandha articles

otc melatonin pills

methylphenidate ritalin consiquences for neurontin crestor and adverse reactions iwth cranberries hoodia warnings melatonin getpharma

breast augmentation dd cup

finasteride enlarged prostrate cipro tab atarax 75mg hoodia shortage rhinocort side effects

thai green curry recipe bamboo shoots

clonazepam klonopin graham bunn and model shoot cephalexin and chlamydia lawsuits on celexa mercury intenational assistance and cla

breast augmentation new hampshire

benzphetamine vs phentermine hpt and clomid photos of allegra versace pregnant and taking prilosec price of zyrtec

hoodia buy cheap 34546

atarax side effects shoot through how to shoot a goose zetia blurry vision unknown soldier accutane

ultram tablets

dexedrine dosage green tea home fragrance mist hgh youth fomula aleve and surgery clomid causes

ativan and cipro

cost of fexofenadine articcat trouble shoot allegra beck photo free sample of cytotec us satalite shoot

navt to shoot down satellite

methylphenidate cost cymbalta smoking article altace breast augmentation surgeons in sd dilantin kapseals

contraindications to lipitor

cialis price buspar addictive cialis powered by phpbb kodak vr35 point and shoot ultracet 2000 2002 jelsoft enterprises ltd

cancer femara drug

is oxycodone percocet what is claritin viagras effect on women natural remidies for zoloft withdrawl systems arizona peach green diet tea

crestor mississippi research state university

test propionate prednisone forums hoodia fomula uk buy propecia online cheap pharmacy brite ight bait store

pronounce ultram

diet with phentermine zyprexa litigation has it been settled paxil law suit 2008 new wholesale hoodia diet tabs ultram increased alertness pharmacy

soma neuromuscular integration

test prop vasotec 10mg zyprexa 10 hoodia gordini weightloss 2.5 mg lexapro

tv commercial zyrtec

dosage of sildenafil citrate second month on clomid generic viagra quick shipping fosamax joint pain does maxalt cause heart problems

coral calcium supreme 0d 0a

diazepam and valium dolor ibuprofeno tramadol clomid missed period not pregnant npr prilosec can other drugs interact with cephalexin

matcha japanese green tea

amoxicillin clav diflucan furosemide where to buy nu hgh sprays hgh size needle cymbalta and eyes problems

human growth hormone stimulator

celebrex-coupons zocor competitors buy order discount pravachol free shipping manie heart defects antidepressants paxil what does seroquel treat

symptons of flomax

results of winstrol candida esophagitis diflucan breast augmentation pocket revision lipitor eye can viagra cause surgery complications

prozac band simon

adipex diet absolute best male enhancement pill prednisone for tendinitis melatonin nitemares nexium side affect problems

side effects indomethacin and prednisone combined

amoxicillin and clavulanate tentex royal lipitor trouble urinating colchicine and vision loss does prozac make you fat

prednisone crohn

low testerone naprosyn and tingling cheap fedex tramadol kamagra prescription actonel boniva fosamax side effects

what is in rogaine

fast kamagra viagra and phentermine interaction iv protonix buy tramadol online drugs similiar to viagra

paul vantin

cheap kamagra prednisone cialis combine hoodia 450 migraine coreg grimace shoot

over night cialis

percocet watson 540 evista raloxifene missouri tentex royal johnson zyrtec otc consumer digital cameras shoot image models lenses

diflucan allegra

apap-with-codeine arimidex canada lopressor and jaw pain viagra viagra online buy viagra trouble shoot plumbing

the game shoots fifty

how to buy phentermine cholesterol et nolvadex green vs red tea information on antidepressants like cymbalta photo shoot 4109

lipitor lovastatin

vicodin watson 540 dr mirabile breast augmentation pics atrovent nasal spray 0 03 proscar finasteride hawaii changing from lexapro to effexor

dog poisoning seroquel

fluoxetine dosage pamelor 25mg motrin and headaches casodex bicalutamide texas synthroid and caffeine

augmentation breast financing

celebrex-cost singulair aerator motor allegra print and imaging pekin il evista real dad augmentin 875 mg side effects

people using lexapro

generic vardenafil year of original purim avodart injections is ultram a controlled drug what does glucophage do

medrol dosepak 5mg

get ritalin cost of augmentin 875 rainbow brite dvd viagra and dogs blood cozaar pressure

lexapro peak effects

cheapest acomplia on effexor you cant cum green tea herb and acne can i take tylenol with mobic buy online cozaar

synthroid toxicity

abuse of soma breast augmentation before and after photo effexor overdose effects lexapro drug content and purpose hoodia gordonii complex

rendevous allegra hotel adelaide

percocet vicodin smoking hoodia photo shoot 2096 using cialis with trimix famvir for shingles

beta brite message board

acetaminophen-with-codeine tevau tramadol search tevau tramadol buspar cause early period prednisone and polymyalgia cialis causes muscle ache because

breast augmentation costs in canada

buy acomplia online augmentin 12h neurontin flexeril interaction amaryl and actos korn kobblers don't shoot the bartender

risperdal class action lawsuits

levitra online potential toxic side effect for lasix aciphex 20 mg drug interaction tramadol cymbalta elimite no prescription

azithromycine vs augmentin

finasteride administration dyi photo shoot pronounce ultram affect side zyban accutane guild paternity rights legal dictionary

zoloft and attacks heart

generic soma playboy shoot in bathroom biphasic on 100mg clomid now monophasic celexa effects on voice and speech celebrex inventors

the best melatonin

fluoxetine and alcohol prescription strength aleve augmentin clav k missed dosage prometrium pregnancy picture of cialis

cheap generic zocor

ambien online viagra weight loss can xanax be taken with effexor diabedics taking prednisone prednisone step down dosing dog

green tea help w allergies

ativan xanax mega green tea diet health mens dose green tea help lose weight flomax australia blood pressure rise medication lisinopril

green tea prices

cheap viagra does maxalt cause heart problems clomid testicular axis lexapro spinal therapy bodybuilding ultimate hgh bodybuilding

different prozac formulas

adipex and alcohol prozac klonopin albers medical lipitor diet hoodia supplement decafinated mega green tea extract