-2

For example if I had a triangle with these properties

triangle(100, 300, 200, 200, 300, 300);

or just think of it as

triangle(x1, y1, x2, y2, x3, y3);

How would you write an if statement to check if mousePressed() is within the triangle shape?

Anonymous
  • 9
  • 2
  • 8
  • Have you tried google at all? Check out [this](http://stackoverflow.com/questions/2049582/how-to-determine-a-point-in-a-2d-triangle) and [this](http://www.blackpawn.com/texts/pointinpoly/) and [this](http://mathworld.wolfram.com/TriangleInterior.html) for a start. Please **try something** and post an [MCVE](http://stackoverflow.com/help/mcve) if you get stuck. – Kevin Workman Feb 09 '16 at 19:35

1 Answers1

0

As Kevin pointed out, this is an already well documented question and answer.

For fun, there's a hacky workaround to avoid the math using PShape. There is an undocumented contains() function which checks is an x,y pair is inside all the points of a PShape. That's nice, since this applies for all sort of other shapes, not just triangles. It's a point in polygon test instead of a point in triangle test. There is a catch however. This function isn't documented because it's probably still experimental so there are gotchas:

  • it works on PATH type only PShapes
  • PATH type PShapes that aren't loaded (from an SVG file for example) don't render using the shape() function, so you have to manually loop through vertices and draw the shape

Here's an example:

PShape triangle;

void setup(){
  size(100,100,P2D);
  noStroke();

  //create the triangle as PATH type PShape 
  triangle = new PShape(PShape.PATH);
  //add it's vertices
  triangle.vertex(50,10);
  triangle.vertex(10,90);
  triangle.vertex(90,90);

}
void draw(){
  background(255);
  //check if point is inside triangle
  if(triangle.contains(mouseX,mouseY)){
    fill(127);
  }else{
    fill(0);
  }
  //render triangle accessing the vertices previously set
  beginShape(TRIANGLE);
  for(int i = 0 ; i < triangle.getVertexCount(); i++){
    PVector v = triangle.getVertex(i);
    vertex(v.x,v.y);
  }
  endShape(CLOSE);
}

However, in practice you might find using the math approach simpler (since there are less workarounds to worry about).

George Profenza
  • 50,687
  • 19
  • 144
  • 218