Skip to content

Instantly share code, notes, and snippets.

@calderonsteven
Created June 18, 2013 16:59
Show Gist options
  • Select an option

  • Save calderonsteven/5807230 to your computer and use it in GitHub Desktop.

Select an option

Save calderonsteven/5807230 to your computer and use it in GitHub Desktop.
get intersections between lines
// line segment class
class LineSegment {
// storage for begin/end points
PVector begin;
PVector end;
PVector intersection;
LineSegment(PVector begin, PVector end){
init();
this.begin = begin;
this.end = end;
}
LineSegment(int x1, int y1, int x2, int y2){
init();
begin = new PVector(x1, y1, 0);
end = new PVector(x2, y2, 0);
}
void init(){
intersection = new PVector(0, 0, 0);
}
void display(){
line(begin.x, begin.y, end.x, end.y);
}
boolean getIsIntersecting(LineSegment other_line){
// see explanation here: http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/
float denom = ((other_line.end.y - other_line.begin.y)*(end.x - begin.x)) -
((other_line.end.x - other_line.begin.x)*(end.y - begin.y));
float nume_a = ((other_line.end.x - other_line.begin.x)*(begin.y - other_line.begin.y)) -
((other_line.end.y - other_line.begin.y)*(begin.x - other_line.begin.x));
float nume_b = ((end.x - begin.x)*(begin.y - other_line.begin.y)) -
((end.y - begin.y)*(begin.x - other_line.begin.x));
float ua = nume_a / denom;
float ub = nume_b / denom;
if(ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f){
// Get the intersection point.
intersection.x = begin.x + ua*(end.x - begin.x);
intersection.y = begin.y + ua*(end.y - begin.y);
return true;
}
return false;
}
PVector getIntersection(){
// return point of intersection
return intersection;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment