Checks if a Vector2D is contained by a polygon. - Java 2D Graphics

Java examples for 2D Graphics:Polygon

Description

Checks if a Vector2D is contained by a polygon.

Demo Code

/*//w  w  w  .  ja v  a 2s  .  c  o  m
 *  Flingbox - An OpenSource physics sandbox for Google's Android
 *  Copyright (C) 2009  Jon Ander Pe?alba & Endika Guti?rrez
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import java.util.ArrayList;

public class Main{
    /**
     * Checks if a Vector2D is contained by a polygon.
     * It's based on Winding number algorithm.
     * More info at {@link http://en.wikipedia.org/wiki/Winding_number}
     * 
     * @param polygon polygon's Vector2Ds
     * @param Vector2D Vector2D to be checked
     */
    public static boolean polygonConatinsPoint(Vector2D[] polygon,
            Vector2D Vector2D) {
        final int Vector2DsCount = polygon.length;
        final float px = Vector2D.i, py = Vector2D.j;
        int c = 0;
        for (int i = 0; i < Vector2DsCount; i++) {
            Vector2D v1 = polygon[i];
            Vector2D v2 = polygon[(i + 1) % Vector2DsCount];
            if ((v1.j < py) && (v2.j > py)) {
                if (v1.i > px || v2.i > px)
                    c++;
                // Check if Vector2D is at the left or the right side of the object
                //final float segmentAtX = ((v2.i - v1.i) / (v2.j - v1.j)) * (py - v1.j) + v1.i;
                //if (segmentAtX > px) 
                //   c++;
                //else if (segmentAtX == px)
                //   return true; // is over the bounder
            } else if ((v1.j > py) && (v2.j < py)) {
                if (v1.i > px || v2.i > px)
                    c--;
                // Check if Vector2D is at the left or the right side of the object
                //final float segmentAtX = ((v2.i - v1.i) / (v2.j - v1.j)) * (py - v1.j) + v1.i;
                //if (segmentAtX > px) 
                //   c--;
                //else if (segmentAtX == px)
                //   return true; // is over the bounder
            }
        }
        return c != 0;
    }
}

Related Tutorials