How can I determine whether a 2D Point is within a Polygon?

前端 未结 30 2679
醉梦人生
醉梦人生 2020-11-21 05:06

I\'m trying to create a fast 2D point inside polygon algorithm, for use in hit-testing (e.g. Polygon.contains(p:Point)). Suggestions for effective tech

30条回答
  •  不要未来只要你来
    2020-11-21 06:07

    Java Version:

    public class Geocode {
        private float latitude;
        private float longitude;
    
        public Geocode() {
        }
    
        public Geocode(float latitude, float longitude) {
            this.latitude = latitude;
            this.longitude = longitude;
        }
    
        public float getLatitude() {
            return latitude;
        }
    
        public void setLatitude(float latitude) {
            this.latitude = latitude;
        }
    
        public float getLongitude() {
            return longitude;
        }
    
        public void setLongitude(float longitude) {
            this.longitude = longitude;
        }
    }
    
    public class GeoPolygon {
        private ArrayList points;
    
        public GeoPolygon() {
            this.points = new ArrayList();
        }
    
        public GeoPolygon(ArrayList points) {
            this.points = points;
        }
    
        public GeoPolygon add(Geocode geo) {
            points.add(geo);
            return this;
        }
    
        public boolean inside(Geocode geo) {
            int i, j;
            boolean c = false;
            for (i = 0, j = points.size() - 1; i < points.size(); j = i++) {
                if (((points.get(i).getLongitude() > geo.getLongitude()) != (points.get(j).getLongitude() > geo.getLongitude())) &&
                        (geo.getLatitude() < (points.get(j).getLatitude() - points.get(i).getLatitude()) * (geo.getLongitude() - points.get(i).getLongitude()) / (points.get(j).getLongitude() - points.get(i).getLongitude()) + points.get(i).getLatitude()))
                    c = !c;
            }
            return c;
        }
    
    }
    

提交回复
热议问题