Skip to content

Instantly share code, notes, and snippets.

@mlabbe
Created July 29, 2015 01:01
Show Gist options
  • Select an option

  • Save mlabbe/9aad46678c032c799983 to your computer and use it in GitHub Desktop.

Select an option

Save mlabbe/9aad46678c032c799983 to your computer and use it in GitHub Desktop.
Point on side of line - Processing
PVector l1, l2;
PVector pt;
float g_scale = 50.0f;
static final int SIDE_FRONT = 0;
static final int SIDE_BACK = 1;
static final int SIDE_COLINEAR = -1;
static final float COLINEAR_EPSILON = 2.0f; /* fudge */
/* returns one of the three side constants */
int point_on_side(PVector l1, PVector l2, PVector pt)
{
PVector delta = new PVector();
delta.x = l2.x - l1.x;
delta.y = l2.y - l1.y;
PVector pt_delta_l1 = new PVector();
pt_delta_l1.x = pt.x - l1.x;
pt_delta_l1.y = pt.y - l1.y;
PVector perp = new PVector(-delta.y, delta.x,0);
perp.normalize();
float sign = pt_delta_l1.dot(perp);
if (abs(sign) <= COLINEAR_EPSILON)
return SIDE_COLINEAR;
if ( sign > 0.0f )
return SIDE_FRONT;
else
return SIDE_BACK;
}
void setup()
{
size(1280,720,P2D);
l1 = new PVector(50.0f, 10.0f);
l2 = new PVector(250.0f, 500.0f);
pt = new PVector();
}
void draw()
{
background(192);
pt.x = mouseX;
pt.y = mouseY;
/* dot */
strokeWeight(48.0f);
int the_side = point_on_side(l1, l2, pt);
switch(the_side)
{
case SIDE_BACK:
stroke(0,255,0);
break;
case SIDE_COLINEAR:
stroke(255,0,0);
break;
case SIDE_FRONT:
stroke(255);
break;
}
point(pt.x, pt.y);
/* original line */
strokeWeight(2.0f);
stroke(255,0,0);
line(l1.x, l1.y, l2.x, l2.y);
if (mousePressed && (mouseButton==LEFT)) {
l1.x = mouseX;
l1.y = mouseY;
}
if (mousePressed && (mouseButton==RIGHT)) {
l2.x = mouseX;
l2.y = mouseY;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment