Help Understanding a math function
in
Programming Questions
•
7 months ago
Hey all,
So I have a bit of a special situation here. I have an algorithm that my coworker gave me in Javascript for determining if a point is within a shape. It works fine but he got it from somewhere else and we both are not really sure HOW it works per se, just that it works really well. I converted it into a small Polygon class I wrote for this project I'm working on and was wondering if someone could take a look and and maybe help my mind understand this algorithm? I'll be using it a lot and am uneasy about having something so core to my app be out of my understanding.
- class Polygon{
- ArrayList<PVector> points;
- PVector[] ptArray = new PVector[1];
- Polygon(ArrayList<PVector> _points){
- points = _points;
- ptArray = new PVector[points.size()];
- points.toArray(ptArray);
- }
- void addPoint(PVector pt){
- points.add(pt);
- ptArray = new PVector[points.size()];
- points.toArray(ptArray);
- }
- PVector[] getPoints(){
- return ptArray;
- }
- void render (){
- beginShape();
- for(int i = 0; i< ptArray.length; i++){
- vertex(ptArray[i].x, ptArray[i].y);
- }
- endShape(LINES);
- }
- // convenience function to see if a point is within this polygon
- // some pretty gnarly math happening here.
- boolean within(PVector pt){
- boolean inside = false;
- int j = 0;
- float ptX = pt.x, ptY = pt.y, polyXI, polyXJ, polyYI, polyYJ;
- for(int i = 0; i < ptArray.length; i++){
- // j is going to be a second interator
- // we will use ever point and compare it with the next point
- j++;
- if( j == ptArray.length) j = 0;
- //polyXI/polyYI = x/y cordinate of polygon point that goes with index i
- //polyXJ/polyYJ = x/y coordinate of polygon point that goes with index j
- polyXI = ptArray[i].x; polyXJ = ptArray[j].x;
- polyYI = ptArray[i].y; polyYJ = ptArray[j].y;
- //do a little bit of blunt checking to make sure the point is in the general bounds of the polygon
- if( (polyXI < ptY && polyXJ >= ptY) || (polyXJ < ptY && polyXI >= ptY) && (polyYI <=ptX || polyYJ <= ptX) ){
- // there be dragons here... no touching
- if( polyYI + (ptY - polyYI) / (polyXJ - polyXI) * (polyYJ - polyYI) < ptX ) inside = !inside;
- }
- }
- return inside;
- }
- }
- Polygon p;
- void setup(){
- size(400,400);
- smooth();
- background(0);
- ArrayList<PVector> pts = new ArrayList<PVector>();
- pts.add(new PVector(0,0));
- pts.add(new PVector(0,10));
- pts.add(new PVector(10,10));
- pts.add(new PVector(10,0));
- p = new Polygon(
- pts
- );
- println(p.within(new PVector(5, 10)));
- stroke(255);
- noFill();
- }
- void draw(){
- background(0);
- p.render();
- }
1