Skip to content

Instantly share code, notes, and snippets.

View santileortiz's full-sized avatar

Santiago León santileortiz

  • Mexico
View GitHub Profile
@santileortiz
santileortiz / gist:698adbde7b1af1a1e3299886551aa864
Created January 24, 2018 07:40 — forked from ChickenProp/gist:3194723
The Liang-Barsky algorithm for line-rectangle collisions

The Liang-Barsky algorithm is a cheap way to find the intersection points between a line segment and an axis-aligned rectangle. It's a simple algorithm, but the resources I was pointed to didn't have particularly good explanations, so I tried to write a better one.

Consider a rectangle defined by x_min ≤ x ≤ x_max and y_min ≤ y ≤ y_max, and a line segment from (x_0, y_0) to (x_0 + Δ_x, y_0 + Δ_y). We'll be assuming at least one of Δ_x and Δ_y is nonzero.

Image depicting the situation

(I'm working with Flash, so I'll be using the convention that y increases as you go down.)

We want to distinguish between the following cases: