Dynamic polygons
Left/Right to Decrease/Increase the number of vertices in the polygon.
Drag the boxes around to change the shape.
♥0 |
Line 75 |
Modified 2011-11-13 08:03:17 |
MIT License
archived:2017-03-20 09:58:42
ActionScript3 source code
/**
* Copyright antalg ( http://wonderfl.net/user/antalg )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/wPvz
*/
package {
import flash.events.KeyboardEvent;
import flash.display.AVM1Movie;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.Sprite;
public class FlashTest extends Sprite {
private var _handles:Array = []; // Vertex array
private var _polygon:Sprite = new Sprite(); // Polygon sprite
private var _polygonVerts:int = 4; // The polygon vertex count
public function FlashTest() {
addChild(_polygon);
newPolygon(_polygonVerts); // Create new handles
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyD); // Add key controls
}
private function newPolygon(verts:int):void {
for each (var s:Sprite in _handles) // Remove all old handles
stage.removeChild(s);
_handles = []; // Clear handle (vertex) array
var dAngle:Number = 2*Math.PI/verts; // The angle step: (2pi/verts radians)
var angle:Number = 0; // Start angle is 0 radians
var x:Number = 465/2; // Center x of polygon
var y:Number = 465/2; // Center y of polygon
var dist:Number = 128; // Distance from center to each vertex
for(var i:int = 0; i < verts; ++i) { // Create new sprites
var spr:Sprite = new Sprite(); // Draw
spr.graphics.beginFill(0x000000);
spr.graphics.drawRect(-5, -5, 10, 10);
spr.graphics.endFill();
spr.x = x + dist*Math.cos(angle); // Position
spr.y = y + dist*Math.sin(angle);
_handles.push(spr); // Add to handle array
stage.addChild(spr);
spr.addEventListener(MouseEvent.MOUSE_DOWN, controlMD); // Set up mouse events for dragging
spr.addEventListener(MouseEvent.MOUSE_UP, controlMU);
angle += dAngle; // Calculate next angle
}
updatePolygonFill(); // Update fill
}
private function updatePolygonFill():void { // Update the fill
var last:Sprite = _handles[_handles.length-1];
var s:Sprite;
with (_polygon.graphics) {
clear();
lineStyle(2, 0x000000, 0.5);
beginFill(0xAA00AA);
moveTo(last.x, last.y);
for each (s in _handles)
lineTo(s.x, s.y);
endFill();
}
}
private function keyD(e:KeyboardEvent):void {
if (e.keyCode == 37) {
_polygonVerts = _polygonVerts>1?(_polygonVerts-1):_polygonVerts;
// Just a ternary operator (it's very much like a if else statement)
// (boolean operation)?(if true return this):(else return this)
newPolygon(_polygonVerts);
} else if (e.keyCode == 39) {
++_polygonVerts;
newPolygon(_polygonVerts);
}
}
private function controlMD(e:MouseEvent):void {
e.target.startDrag();
addEventListener(Event.ENTER_FRAME, isMoving);
}
private function controlMU(e:MouseEvent):void {
e.target.stopDrag();
removeEventListener(Event.ENTER_FRAME, isMoving);
updatePolygonFill();
}
private function isMoving(e:Event):void {
updatePolygonFill();
}
}
}