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.

Welcome !
Site google-analitix.com just created.

Real content coming soon.
© ISPmanager control panel

software design 2020 mac

Adobe Premiere Pro CS5 Student and Teacher Edition download indisign cs3 mac download oem software autodesk autocad 2008 price discount adobe indesign cs2 download full software cheap erwin data modeler buy

oem downloads

Corel Digital Studio 2010 discount office 2007 enterprise buy cheap sibelius oem autocad 2009 microsoft windows xp tablet pc edition prices

oem software download cs4 mac

download now Lynda After Effects CS5 Essential Training cheap oem software for mac oem adobe elearning suite discount pure network magic oem software p-cad

adobe dreamweaver mx2004 oem download

download online Lynda Photoshop Elements 8 for Windows Essential Training donde puedo comprar el sam broadcaster 4 buy photoshop elements discount buy adobe audition 1.5 spyhunter cheapest

autocad 2008 sale

AD Sound Recorder order purchase flashpaper2 adobe photoshop aetherize filter cheapest buy windows 7 download oem software primavera

buy winamp

cheapest SmartDraw 2010 best buy sibelius 6 acheter etrust management suite order online download microsoft office 2003 cheap cheap final cut

the cheapest dvd copy program

discount AD Sound Recorder microsoft windows 2000 cheap oem software buy cheap adobe premier pro 2.0 buy microsoft works

download adobe acrobat 7.0

download online Adobe Premiere Pro CS5 Student and Teacher Edition download office 2003 buy adobe photoshop cs4 mac oem cheap adobe illustrator cs4 buy cheap isobuster

macromedia studio 8 oem

download online Autodesk 3ds Max 2011 macromedia flashpaper 2 microsoft office 2004 for mac oem order online human software automask buy focus cd cover maker 2.1

adobe audition 1.5

MAGIX Digital Photo Maker 9 order photoshop cs2 buy cheap arcgis download online cheap image doctor 2.0 cheap software trados multiterm

software

buy Screentime for Flash buy and download office mac 2004 bentlry plantspace for sale download now arcgis desktop oem review acrobat 9 -reader download

buy downloadable adobe contribute cs4

download Lynda 3ds Max 2010 Textures and Materials display fusion pro server 2003 enterprise edition order vanderlee unplugged x mac creative free software

oem software stores

WebLog Expert 7 discount unitwriter cheap adobe photoshop download buy online mac illustrator cheap microsoft office

microsoft ofice enterptise 2007

download online Adobe Creative Suite 5 Web Premium Student and Teacher Edition [MAC] adobe photoshop 7 cheap down loads for office 2000 buy online download acrobat 7 pro for mac oem entech power strip

macromedia studio 8 oem

Adobe Acrobat 8 Pro for Mac download cheap software download windows 7 software package center net adobe captivate download buy 3d studio max 7 cheap microsoft office 2007

autotune for cheap

buy cheap SecurityCAM sql 2003 developer edition owl basic bookkeeping buy corel paradox adobe premiere pro cs4 oem

autocad 2007 download

Joboshare DVD to PS3 Converter oem adobe flash catalyst cs5 buy artlantis studio 2 buy download now windows 7 download cheap photo draw v2.0

1clickdvd discount

buy online iShell for MAC buy smartsketch cheap cs5 master collection buy cheap coreldraw creative suite 3 adobe mac

buy indesign cs3 for mac

buy online Autodesk Mudbox 2011 for MAC cheap video converter ulead photo explorer 8.5 oem creative suite 5 web premium adobe acrobat 7 mac

cheap down loads for office 2000

buy cheap Sage ACT! Premium 2012 ulead cd dvd pictureshow 4 smartsketch buy discount photodraw microsoft office 2003

buy microsoft mac online

oem Presonus Studio One Pro 2 microsoft picture it download dvd moviefactory 7 order strucad oem picture it photo premium 9

correl paradox

buy online Microsoft Office OneNote 2007 techsmith snagit cheep oem software buy online cheap oem software cs4 amos sem software price

cheap oem software store

Ashampoo PowerUp 3 download online buying microsoft windows 7 cheap sothink swf quicker oem cakewalk audio creator downloads virtual pc 7 mac download

adobe acrobat 8 for mac buy cheap

Lynda ActionScript 3.0 in Flex Builder Essential Training download online foxpro 9 oem autodesk stitcher buy cheap autocad 2008 download serious magic ultra 2

able2extract

discount Core Data Editor [MAC] buy sibelius softwarepackagecenter buy cheap buy snagit cheap eom download software

buy snagit 9

buy Joboshare iPhone Rip 1st email address spider buy oem mac software order download microsoft office 2007 buy microstation

go1984 oem

Lynda AutoCAD 2011 New Features oem oem version of arkaos dmx office for mac order online spyhunter discount promo code adobe premium cs4 oem

homesite 5.5

Autodesk Maya 2011 [MAC] download now mac software downloads -free buy smartsketch buy cheap buy ms project online adobe creative suite 3 web premium (pc)

graphpad discounts

AudioLava 1 buy cheap down loads for office 2000 convertxtodvd 3 cheap download now corel paradox 9 office 2003 professional edition

buy photoshop elements

Lynda Dreamweaver CS4 Essential Training buy online examdiff or ftpvc software human software automask oem 15 little snitch adobe indesign cs3 mac

cheap ms office suite in german

cheapest Lynda Illustrator CS4 One-on-One: Mastery adobe photoshop cs4 oem cheap software for pc cheap software adobe mac order bias soundsoap ulead photo explorer 8.5

graphpad prism

MAGIX Digital Photo Maker 8 buy oem-software 3ds max 2009 download download online sam broadcaster cheap rates nero 6

cheap adobe audtion

Engraver II [MAC] buy cheap oem software review windows vista ultimate x64 edition included sp1 buy cheap buy avira antivir ispy lan monitor

soft-revew

buy online AutoCAD 2007 adobe page maker 7 microsoft office download for mac cheep order online oem software shop featurecam cheap

microsoft office 2008 mac

download now KennelMate 3.4 staad pro software for sale oem software adobe acrobat professional download faces 4.0 edu purchase contribute adobe

frontpage oem

Lynda AutoCAD 2011 New Features oem download microsoft office 2003 ms visio 2007 download order coreldraw graphics suite 11 download ultramon

macromedia fireworks mx 2004

Cubase 5 download office 2003 download apple final cut express hd 3.5 mac download cheapest quark xpress 8 download cheap fireworks 8

cheap software download

Lynda Photoshop Lightroom 3 Essential Training buy online photoshop cs4mac download ecopy buy publisher 2007 purchase ms office online

cheap downloadable oem software

download online Corel Digital Studio 2010 email-business email extractor 6.4 oem downloadable software windows xp buy macromedia flash mx 2004 download visio 2007 let 6lt s

buy microsoft frontpage 2003

Joboshare MP4 Converter cheapest buy adobe fireworks cs4 mac oem macromedia buy cheap cheap adobe quarkxpress oem

indesign cs3 mac oem

PortSight Secure Access 4 oem buy and download the foundrynuke anydvd hd cheap buy cheap pagemaker 7 download recover my files buy

download frontpage 2003

order ZeusDraw [MAC] buy splitview 2009 cheap oem software store download download microsoft office 2003 professional buy soft cfosspeed

mindmanager cheap

Adobe Flash Catalyst CS5.5 Student and Teacher Edition download online cheap download software ms download software download buy cheap foxit phantom 1.0 x64 download buy avira antivirus online

download microsoft office 2003 cheap

Core Data Editor [MAC] download online windows xp download x64 buy microsoft office xp professional order online cheap oem acdsee systems oem sketchup pro 7

microsoft office 2000 software download from internet

Engraver II [MAC] order online download sibelius web easy professional 8 cost oem coldfusion oem software standard edition buy internet download manager discounted

buy adobe photoshop cs4 extended

download MAGIX Digital Photo Maker 8 noromis photolab fluke lan mapshot cheapest reseller homesite 5.5 microsoft office for mac 2008 oem download

digital power mask

Lynda ColdFusion Builder Essential Training buy cheap adobe acrobat 8 professional for mac buy bentley software download online oem mac and windows software cheap office visio professional 2007

windows 2000 advanced server

download online Microsoft Office Project Professional 2003 adobe indesign upgrade mac download microsoft office 2000 small business download buy cheap price ecotect techsmith

archicad12

oem Lynda Dreamweaver CS4 Essential Training oem software in spanish download microsoft office 2004 for mac order mobipocket creator cakewalk home studio 2004

what is autodesk psg

SmartDraw 2010 cheapest buy photodraw 2.0 downloadable microsoft office software cheap download online photoshop cs4 extended purchase photo draw version 2

cialis professional thailand

klonopin withdrawals rogaine mens dog given lexapro korean word for viagra tricor 145 mg cut half

how long should you take casodex

watson 540 blue creme main green tea hand cream elavil pill sizes diflucan and augmentin lariam litigation

drug reactions to fosamax

soma online protonix joints tramadol resistant trouble shoot myers snow pump what is amoxil

l-tyrosine and zoloft any interactions

ritalin side effects noroxin side effects buy zithromax without a prescription viagra hurt women vytorin versus crestor

shoots leaves and

zolpidem overdose celebrex and aspirin tripak zithromax tussinex hair loss due to prednisone hoodia health

melatonin and colitis cure

prometh-with-codeine cla and weightloss ingredients in allegra lipitor ldl levels same plaque worse car brite indiana

coral calcium 6

klonopin side effects augmentation breast procedure lcd projectors buy soma generic drug for tricor clinical trial exelon

class action against dilantin drug manufacturers

buy cheapest hydrocodone watson 540 online no prescription vogue alice in wonderland photo shoot 0.075 mg generic synthroid youtube horse west nile shoot levitra medical trials

atrovent nasal spray 0 03

percocet price casodex tablet childrens purim play side effects of taking prednisone pills celexa stratera

chag purim chords

syrup-with-codeine atrovent cause glaucoma patient safety goals on coumadin drinking alcohol lamictal canadian nexium price

prednisone lupus side effects mental

soma reviews is there caffine in green tea cnn cymbalta most natural looking breast augmentation celebrex and muscle inflammation

trouble shoot warn xdc 9.5

use of ativan can i buy hoodia drinking alcohol while on clomid accutane teenage growth pamelor multiple sclerosis

breast enhancement implants embrace women natural

zolpidem online paxil 37.5 claritin d causes heart to race natural hoodia side effects stalone on hgh

what is the drug diovan

vicodin high how quickly does claritin green tea chocalte balls plavix sideaffects ttp soma rogers ar

companys that make tramadol

ultram online lisinopril alternative drug tear drop breast augmentation lexapro 30 mg daily prednisone provigil

brite study

get ativan bubble shoot snoopi chitosan health benefits lisinopril advil aleve drops blood count

with zyban

ultram dosage cymbalta recommended dose cymbalta mixed with skelactin allegra hervey bay vicodin versus tramadol

shoot snuggles

percocet side affects elli lily hgh nude shoots fat crestor cells energy college men preparing for photo shoots

arizona green tea flower

vicodin in system snap and shoot takedown machine hoodia gordonii complex buy paxil cr no prescription lexapro drug test

side effects altace

ritalin price nicole scherzinger shoot video beep aldactone price cialis distributors withdrawal from effexor antidepressant