# Collision Detection/Response in Vector-based levels

I have a 2D side scroller whose levels are stored as vectors (that is, a bunch of lines) which looks like this: How would I detect that I'm colliding with one of these lines, and react accordingly (say, slide down the slope, or stand still on a flat platform)? We can assume the player uses an AABB.

• Could you not just do a line-box intersection test? – The Communist Duck May 25 '11 at 10:40
• The Communist Duck: No, he couldn't just do a line-box intersection test. – Olhovsky May 25 '11 at 16:59

You might want to use a physics engine that does the work for you. Even if you get the collision detection right, there is still the problem of the collision response that let's the character slide down a slope, which can be even harder than the actual collision detection.

Box2D can do it for you.

• I'm considering Box2D, but it seems to only do convex polygon shapes. Should I generate polygons from my line segments, or should I just modify the level editor to support polygons? Should they all just be static bodies? Thanks – mpnk121 May 25 '11 at 11:40
• @mpnk121 :polygons are nothing else that a bunch of lines which created a closed shape, it's nothing much diffrent from the lines you are already generating. – Ali1S232 May 25 '11 at 11:47
• @mphk121 the manual.pdf in Box2D/Documentation says in paragraph 4.4 Polygon Shapes: "However, you can create line segments using 2 point polygons" – Maik Semder May 25 '11 at 12:03
• However, it's probably easier if you connect the lines to a convex polygon. The picture in your question-body uses convex polygons anyway. – Maik Semder May 25 '11 at 12:05

for each line (represented by ax+by+c = 0) and each object(which moved from x0,y0 to x1 y1) you have to check if the result of this product is negetive (a*x0+b*y0+c)*(a*x1+b*y1+c). negetive value means there is a collision somewhere(it may be after the both end of line) and the possitive value means there are no collisions. if there realy was a collision then you have to calculate collision point using these formulas and check if that's somewhere between two ends of your line.

we want to calculate the collision point of these 2 lines :

ax+bx+c = 0
(x1-x0)x+(y1-y0)y - (x1-x0)x0+(y1-y0)y0 = 0


so we set these 3 parameters for comuting ease:

a' = x1 - x0
b' = y1 - y0
c' = -(a' * x0 + b' * y0)


and now our problem is :

ax +by +c  = 0;
a'x+b'y+c' = 0;


and then you can have x',y'(collision coordinates)

x' = -(c/b + c') /(a' + b'/b*a)
y' = -(c/a + c') /(b' + a'/a*b)


after that to check if it's inside the line fragment you have to check if (x0-x')*(x1-x')+(y0-y')*(y1-y') is a negetive value, if yes you have a real collision if not the object is past from sides of your line.