Background of Triangular objects

// mouse inside triangle question
// 2D only!
/*
as background and age of "jbott" is unknown 
i want try to help with the first step, what i copy from
https://stackoverflow.com/a/13301035
*/

int plong = 3;                     // point array length        
PVector[] p = new PVector[plong];  // point array
PVector pm;                        // mouse
PShape t;                          // triangle strip shape
//_________________________________________________
void setup() {
  size(200, 200);
  p[0] = new PVector( 20, 30);     // test points
  p[1] = new PVector( 40, 80);
  p[2] = new PVector( 120, 60);
  pm = new PVector( 0, 0);         // for mouse pos

  t = createShape();               // try a shape instead triangle primitiv
  t.beginShape(TRIANGLE_STRIP);
//  t.fill(0, 200, 200);
  t.noStroke();
  t.vertex(p[0].x, p[0].y);
  t.vertex(p[1].x, p[1].y);
  t.vertex(p[2].x, p[2].y);
  t.endShape();
}
//_________________________________________________
void draw() {
  background(0, 200, 0);
  pm.x = mouseX;
  pm.y = mouseY;
  if ( over_t(pm, p[0], p[1], p[2]) ) t.setFill(color(200, 0, 0)); else t.setFill(color(0, 0, 200));
  shape(t, 0, 0);
}
//_________________________________________________
boolean over_t(PVector pm, PVector p1, PVector p2, PVector p3) {
  float alpha = ((p2.y - p3.y)*(pm.x - p3.x) + (p3.x - p2.x)*(pm.y - p3.y)) /
    ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y));
  float beta = ((p3.y - p1.y)*(pm.x - p3.x) + (p1.x - p3.x)*(pm.y - p3.y)) /
    ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y));
  float gamma = 1.0 - alpha - beta;
  if ( gamma > 0 && alpha > 0 && beta > 0 ) return true;
  return false;
}

1 Like