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?
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?
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:
PATH type only PShapesPATH 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 shapeHere'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).