Suggestion-Box
Suggestion-Box copied to clipboard
Determine if point is inside polygon
Hello! Maybe it will be more clear, if I try to explain it with image:
So, the question is, what kind of algorithm can be used to determine, is certain point inside of polygon or not. By saying "inside of polygon" I mean the point 1. And, respectively, points 2 and 3 are not inside of it.
I don't know if you need some sort of calculation, or if only the result is important. If only the result matters, in a canvas, you could draw a color-filled polygon using beginShape and endShape(CLOSE) :
beginShape(); vertex(20, 20); vertex(100, 20); vertex(60, 30); vertex(60, 100); vertex(10, 60); endShape(CLOSE);
Replace above random coordinates with your own polygon's coordinates
Then you can check the pixel color of your point with get(x,y)
If your point's pixel color matches your polygon's fill, the point is inside the shape. Else, it's outside.
This suggestion would most likely not make a whole video. It is quite simple to do and a solution is even given above. I recommend closing this issue as it isn't suitable for the channel.
@shiffman
This is a nice little problem. We used this problem to interview candidates. I still use it today with my students.
When I need to check if Mouse in a poligono I use to sum all the angles between the vectors of each vertex with the point (mouseX, mouseY) and check if it gets 2π in total. If the point is inside the Shape, the sum will be 2π, if not, will be 0. Let me show you:
Thats the function I made to do it. The poligono need to be an array of vertex.
function isMouseOverPoligono(poligono){
let angleSum=0;
for(let i=0;i<poligono.length;i++){
vector1=new p5.Vector(poligono[i][0]-mouseX, poligono[i][1]-mouseY);
if(i===poligono.length-1){
vector2=new p5.Vector(poligono[0][0]-mouseX, poligono[0][1]-mouseY);
}else{
vector2=new p5.Vector(poligono[i+1][0]-mouseX, poligono[i+1][1]-mouseY);
}
angleSum+=vector1.angleBetween(vector2);
}
if(round(angleSum,5)===round(2*PI,5)){
return true;
}
return false;
}