Search code examples
actionscript-3

Creating a polygon in ActionScript 3 from a set of coordinate pairs


I'm making an app in Flash, and I want to define some polygons which I can bind hover events to to add annotations to an image. I can create these normally in Flash, but I want to load some external data, a list of coordinates, and create the polygons with ActionScript.

Obviously they're just hotspots, so I want them to be invisible, but searching for my problem only shows results for drawing polygons from coordinates using the graphics property of a movieclip.

The data doesn't ever change, so it would be possible to just draw all the polygons manually with the pen tool, but the data is being used elsewhere, so it would be much easier to maintain if I could add new zones just by updating the text file.


Solution

  • var pointsRawXML:String = '<mypoints>\n<point x="100", y="100 />\n<point x="100", y="0 />\n<point x="0", y="0 />\n<point x="0", y="100 />\n</mypoints>';
    

    Will give you:

    <mypoints>
        <point x="100", y="100 />
        <point x="100", y="0 />
        <point x="0", y="0 />
        <point x="0", y="100 />
    </mypoints>
    

    Then you load and parse it:

    var points:XML = new XML(pointsRawXML);
    
    var pointsXMLNodeList:XMLList = points.children();
    
    var i:uint = 0;
    
    var pointsVector<Point> polygonPoints = new Vector<Point>();
    
    for(i = 0; i < pointsXMLNodeList.lenght(); ++i) {
        var tmpXML:XML = XML(pointsXMLNodeList[i]);
        var pX:Number = tmpXML.attribute("x") as Number;
        var pY:Number = tmpXML.attribute("y") as Number;
        var p:Point = Point(pX, pY);
        polygonPoints.push(p);
    }
    

    Now you can draw out the polygon inside the graphics object of a sprite:

    //Note we can recycle the "i" variable
    var polyContainerSprite:Sprite = new Sprite();
    polyContainerSprite.graphics.beginFill(0, 1);
    
    for(i = 0; i < pointsVector.length; ++i) {
        if(i == 0) {
            polyContainerSprite.graphics.moveTo(pointsVector[i].x, pointsVector[i].y);
        }else {
            polyContainerSprite.graphics.lineTo(pointsVector[i].x, pointsVector[i].y);
        }    
    }
    
    stage.addChild(polyContainerSprite);
    

    Something like that should work. Note all that code is untested and it's been about a year since I've actually made anything in flash. lol so test and if you have any questions/concerns let me know I'll help clarify.

    Also note that you're going to need to basically adjust this code to "loop" 'n' times, for each poly/sprite that you need. Also note you can save your XML into files and just load them up sing the URLLoader object, and casting the data to an XML.