Wednesday, March 9, 2016

Detecting Collisions in 2D

Introduction
Let's say a game object is in 2 positions over frame updates.  The 2 positions form a line L1.  To determine if the game object collided with a line L2, we look for the presence of an intersection.

We can detect the presence of an intersection (we don't care where it is) by only looking at the slopes between L1's start point and L2's endpoints, and between L2's start point and L1's endpoints.  If L1's slope is between the 2 slopes of L1's start point and L2's endpoints, and also if L2's slope is between the 2 slopes of L2's start point and L1's endpoints, a collision occurred.


Caveats
I have not compared efficiency to other methods.  However this requires no dot product calculations thus no need for taking the cosine.  [If you know of other methods and would like to share - please post a comment!]


Process


Detect the presence of any intersection between line L1 from x1,y1 to x2,y2, and L2 from x3,y3 to x4,y4.


Figure 1, Two Lines L1 and L2



In Figure 1 above, the slopes of the lines are:

For L1, slope m1 = (y2-y1)/(x2-x1)

For L2, slope m2 = (y4-y3)/(x4-x3)

----------------------------------------------------------------------------------------------


Now we can calculate the slopes between x1,y1 and x3,y3, between x1,y1 and x4,y4, and between x3,y3 and x2, y2, as shown in Figure 2 below:



Figure 2, Additional Lines L14, L13, and L32


In Figure 2 above, the slopes of the lines are:

For L14, slope m14 = (y4-y1)/(x4-x1)

For L13, slope m13 = (y3-y1)/(x3-x1)

For L32, slope m32 = (y2-y3)/(x2-x3)

We also added L31, slope m31 = (y1-y3)/(x1-x3)


An intersection exists (and thus a collision occurred) if:

( m14 > m1 > m13 ) || (m14 < m1 < m13 )

&&

( m31 > m2 > m32 ) || (m31 < m2 < m32 )



No comments:

Post a Comment