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).