DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

# Intersecting Lines

04.10.2012
| 9321 views |
`        `
```
void intersect()
{
float m1,m2,b1,b2,ix,iy;
Position p1a = new Position(mouseX, mouseY);
Position p1b = new Position(points[maximum-1]);
Position p2a = new Position();
Position p2b = new Position();

strokeWeight(4);
stroke(0,255,0);
line(p1a.x, p1a.y, p1b.x, p1b.y);

// comparison line segment
m1 = (p1a.y - p1b.y) / (p1a.x - p1b.x);
b1 = p1a.y-m1*p1a.x;

// cycle through each line segment on the gesture backwards
for (int i = maximum-1; i > 0; i--) {

//if (points[i].x < 0 && points[i].y < 0) { continue; }

p2a.set(points[i]);
p2b.set(points[i-1]);

// second line segment
m2 = (p2a.y - p2b.y) / (p2a.x - p2b.x);
b2 = p2a.y - m2*p2a.x;

if (m1 != m2) { // if they're not parallel

// find the intersection
ix = (b2-b1)/(m1-m2);
iy = m1*ix+b1;

// is the intersection on the line segments?
if (ix > min(p1a.x, p1b.x) && ix < max(p1a.x, p1b.x) &&
iy > min(p1a.y, p1b.y) && iy < max(p1a.y, p1b.y) &&
ix > min(p2a.x, p2b.x) && ix < max(p2a.x, p2b.x) &&
iy > min(p2a.y, p2b.y) && iy < max(p2a.y, p2b.y)) {

if (i_count < i_max) {
intersects[i_count].set(ix, iy);
i_count++;
} else {
for (int j = 0; j < i_max-1; j++) {
intersects[j].set(intersects[j+1]);
}
intersects[i_max-1].set(ix, iy);
}

println("something");
// send the points to the shape object
s.set(points, i);
reset();
break;
}
}
}
```
`    `
"Starting from scratch" is seductive but disease ridden