I’m trying to make a program that will detect if the mouse is inside a triangle or not. It has to be any type of triangle. My idea is taking a triangle ABC and the mouse point K and calculating the areas Aabc Aabk Aakc Akbc and figuring out that
if Aabc- (Aabk+Aakc+Akbc) = 0 the point is inside. The function I’m using to find the area is making a matrix 3x3 where column one has x1,x2,x3 and column two has y1,y2,y3 and last column is just filled with ones. This function is mathematically correct but in the code it doesnt work well for the last 3 areas, giving me weird values. I’ll paste down the code. (The notes are in italian, sorry about it but I’m in quite of an hurry and it doesn’t seem hard to follow)
int mK = 255;
int K;
int bgr = 220;
float x1 = 200;
float x2 = 600;
float x3 = 400;
float y1 = 500;
float y2 = 500;
float y3 = 100;
float A;
float A1;
float A2;
float A3;
float At;
void setup(){
size (800,600);
}
void draw(){
//Aree calcolo
A = abs(x1*y2*1+y1*1*x3+1*x2*y3-y1*x2*1-x1*1*y3-1*y2*x3)/2;
A1 = abs(x1*y2*1+y1*1*mouseX+1*x2*mouseY-y1*x2*1-x1*1*mouseY-1*y2*mouseY)/2;
A2 = abs(x1*mouseY*1+y1*1*x3+1*mouseX*y3-y1*mouseX*1-x1*1*y3-1*mouseY*x3)/2;
A3 = abs(mouseX*y2*1+mouseY*1*x3+1*x2*y3-mouseY*x2*1-mouseX*1*y3-1*y2*x3)/2;
At = A1+A2+A3;
//Resetta lo sfondo e i colori
background(bgr);
K=255;
//Disegna i triangoli
fill(K);
triangle(x1,y1,x2,y2,x3,y3);
triangle(x1,y1,x2,y2,mouseX,mouseY);
triangle(x1,y1,mouseX,mouseY,x3,y3);
triangle(mouseX,mouseY,x2,y2,x3,y3);
//Mostra i valori
fill(bgr);
rect(0,0,200,200);
fill(0);
text("A = " + A,10,20);
text("A1 = " + A1,10,30);
text("A2 = " + A2,10,40);
text("A3 = " + A3,10,50);
text("At = " + At,10,60);
text("mX = " + mouseX,10,70);
text("mY = " + mouseY,10,80);
}