[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Line Collision



think about it this way:

if the line is fully left, fully right, fully above or fully beneath
the rectangle, it's not close to the rectangle.

to find the closest approach to the rectangle you usually equate the
rectangle's border lines with the line to be compared as a function:

with exception of vertical lines, a line always has a "rise", that is
a number of y pixels for any x pixel crossing the x axis at a vertical
offset, mathematically that's the classically linear function
expressed with f(x): y = ax + b. Equating that with the lowest and
highest x coordinates of the rectangle gives you two equations y = a *
left + b and y = a * right + b which, when solved for y can then be
compared with the rect's top and bottom coordinate. the rectangle is
obviously crossed if one of the variables is inside the vertical
interval or if they are on opposite sides of the vertical interval; in
code, that's roughly summarized with the following if line:

if ((a * left + b) < bottom and (a * right + b) > bottom) or ((a *
left + b) > top and (a * right + b) < top)):

Welcome to the world of linear algebra. from here onwards you only
need to get used to it enough to figure the case of a vertical line
too.

cheers!
mar77i