Point in Polygon

Actionscript:
  1. // function found here:
  2. // http://www.alienryderflex.com/polygon/
  3. function pointInPolygon(x:Number, y:Number, polyX:Array, polyY:Array):Boolean{
  4.     var j:int = polyX.length - 1;
  5.     var oddNodes:Boolean = false;
  6.     for (var i:int=0; i <polyX.length; i++) {
  7.     if (polyY[i] <y && polyY[j]>= y ||  polyY[j] <y && polyY[i]>= y) {
  8.  
  9.       if (polyX[i] + (y - polyY[i]) / (polyY[j] - polyY[i]) * (polyX[j] - polyX[i]) <x) {
  10.         oddNodes = !oddNodes;
  11.       }
  12.     }
  13.     j = i;
  14.   }
  15.   return  oddNodes;
  16. }
  17.  
  18. // draw an overly complex poly and store all  x y coords
  19. var pX:Array= new Array();
  20. var pY:Array = new Array();
  21. graphics.beginFill(0xCC0000);
  22. for (var i:int = 0; i<60; i++){
  23.     pX[i] = Math.random()*stage.stageWidth;
  24.     pY[i] =Math.random()*stage.stageHeight;
  25.     if (i == 0){
  26.         graphics.moveTo(pX[i], pY[i]);
  27.     }else{
  28.         graphics.lineTo(pX[i], pY[i]);
  29.     }
  30. }
  31. addEventListener(Event.ENTER_FRAME, onLoop);
  32. function onLoop(evt:Event):void {
  33.        alpha = 1;
  34.        if (pointInPolygon(mouseX, mouseY, pX, pY)){
  35.             alpha = .5;
  36.        }
  37. }

This snippet shows how to test to see if a point is inside a polygon. This may not really be useful as hitTestPoint() is likely faster - however this could be modified for other purposes such as polygon to polygon collision. This algorithm works nicely on all kinds of polygons ... convex, concave etc...

I found this algorithm in an article by Darel Rex Finley ... here.

I've used this function in Processing a few times...

This entry was posted in graphics algorithms, misc and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. 62316e
    Posted November 11, 2010 at 2:50 am | Permalink

    I love u!

    Btw, is there a way to get intersection point?

  2. Posted November 22, 2010 at 3:59 pm | Permalink

    thanks. I think this post might help with intersections.

    http://actionsnippet.com/?p=956

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*