Moving elements from one place to another - actionscript-3

Im trying to move elements from one place to another place by randomly telling where to go from an array. But it is not acting as I was hoping it would.
the code is this
public class Main extends MovieClip
{
private var positions:Array = [ 0, 100, 200 ];//different X positions
public function Main()
{
for( var i:int = 0; i < 3; i++)
{
var box:Sprite = new Sprite();
box.graphics.beginFill( Math.random()*0xffffff );
box.graphics.drawRect( 100* i, 0, 80, 80);
box.graphics.endFill();
this.addChild( box );
box.addEventListener(MouseEvent.CLICK, onBoxClick);
}
}
private function onBoxClick( ev:MouseEvent ):void
{
var currentObj:Sprite = ev.currentTarget as Sprite;
var randomNumber:int = Math.random() * positions.length;
currentObj.x = positions[ randomNumber ];
currentObj.y = 200;
positions.splice( randomNumber, 1 );
}
}
as you can see i remove the X position that was given so that 2 elements can have the same position on the stage.But what the code does is it takes the current X position of the element and it adds to that the new X position. So if i click on element 1 and get position 2, click on element 2 and get position 1 and click on element 3 and get position 0 it would be this:
element1.x (0) + 200 = 200;
element2.x (100) + 100 = 200;
element3.x (200) + 0 = 200;
and they will be all in the same spot ( 1 over other).
and what I want is to do This:
element1.x (no matter where it is ) + 200 = 200;
element2.x (no matter where it is ) + 100 = 100;
element3.x (no matter where it is ) + 0 = 0;
I tried doing this
currentObj.x = 0 + positions[ randomNumber ];
or
currentObj.x = stage.x + positions[ randomNumber ];
but then it (the current element) still counts its current location as the '0' and adds to it.
Am i missing something?

Change this line :
box.graphics.drawRect( 100* i, 0, 80, 80);
By this :
box.graphics.drawRect(0, 0, 80, 80);
box.x = 100 * i;
It should work better then.
Your problem is you're drawing from a displaced point in the "box". So, when you're moving it's x, the displacement is summing up.
Drawing it at a 0 point will allow you to remove that offset.

Related

How to change MovieClip transparency based on mouse position?

So, I'm trying to make a grid of rectangles each get more transparent the closer the mouse is to it.
Using some basic maths, I thought I had got it, but instead it seems I got a weird graphic bug(maybe?) shown here:
The middle of the rings is where the mouse is.
Part of code that deals with transparency:
private function update(e:Event = null):void
{
for (var i:int = 0; i < buttons.length; i++) {
lightFact = getDistance(buttons[i])
lightBrightness = lightPower - (lightFact * 10)
buttons[i].alpha = lightBrightness
}
}
getDistance is just getting distance from the block to the mouse.
Each rectangle is a movie clip, if that matters.
If you are trying to do this:
Then I think your problem is basically that your alpha value is ranging from 0 to about 3000 or something like that. That's going to cause strange effects. The value needs to range smoothly from 0 to 1 (so it needs to be a floating point number as in Number).
Here is the code which generated the image above which I wrote for you that will get you started in the right direction:
package
{
import flash.display.*;
import flash.events.*;
public class lightFactTest extends MovieClip
{
private var boxesArray: Array = new Array();
private var xDist: Number = 0;
private var yDist: Number = 0;
private var d: Number = 0;
private var size_Glow : Number = 0;
private var size_Radius : Number = 0;
public function lightFactTest(): void
{
// creates a background for rectangles array.
var BG_box: Sprite = new Sprite();
BG_box.graphics.lineStyle();
BG_box.graphics.beginFill(0x080839);
BG_box.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
BG_box.graphics.endFill();
addChild(BG_box);
//# creates a grid of sprites (rectangles).
for (var i:int = 0; i < (stage.stageWidth / 10); i++)
{
for (var j:int = 0; j < (stage.stageHeight / 10); j++)
{
var box: Sprite = new Sprite();
box.graphics.lineStyle();
box.graphics.beginFill(0xFFFFFF);
box.graphics.drawRect(0, 0, 10, 10);
box.graphics.endFill();
addChild(box);
box.x += i*10; //+ 50;
box.y += j*10; //+ 50;
boxesArray.push(box);
}
}
addEventListener(Event.ENTER_FRAME, lightCalc);
}
private function lightCalc(e: Event): void
{
size_Glow = 3.5;
size_Radius = 0.64;
//# iterates through the array calculating each distance and then alpha.
for (var i:int = 0; i < boxesArray.length; i++)
{
xDist = Math.abs(stage.mouseX - boxesArray[i].x);
yDist = Math.abs(stage.mouseY - boxesArray[i].y);
//var d: Number = Math.pow(xDist * xDist + yDist * yDist, 0.5);
d = Math.sqrt(xDist * xDist + yDist * yDist) / (size_Radius / 5);
//# This is the code that you really need to focus on...
boxesArray[i].alpha = Math.min(1 / d * 10, 1 ) * (Math.PI / 0.5 - Math.min(size_Radius, 0) ) * size_Glow;
}
}
}
}
Hope that helps!

How to create stair effect

So Im trying to constantly add elements on the stage and those elements to have a specific X and Y
what i mean and what i want to get is a stairway effect (up and down) :
lets say 1st element is 100 pix above stage.Y
2nd element: Y is 1st element.y + 2nd element.height and its X position is 1st element.x + 2nd element.width(it appears immediately after we can see the whole body of 1st element)
3rd element : Y is 2st element.y + 3nd element.height and its X position is 2st element.x + 3nd element.width(it appears immediately after we can see the whole body of 2st element)
and the last element before the stairway effect goes down will be stage.stageheight - 100
like in this picture
Yet I dont know how to do this (I know i have to put it in a for loop and in there to have a if statement that checks every time for the up and down border (stage.stageHeight - 100 and stage.Y + 100) but i cant figure it out)
what i have so far is this
private var itemsToAnimate:Array = []
private var magnetBuff:Boolean = false;
private var block:Block = new Block();
private var stage_H:int = stage.stageHeight;
private var block_H:int = block.height;
public function AB_Main()
{
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(evt:Event)
{
this.removeEventListener(Event.ADDED_TO_STAGE, init);
this.addEventListener(Event.ENTER_FRAME, onEveryFrame);
}
private function onEveryFrame(ev:Event):void
{
createItems()
animateItems();
}
private function animateItems():void
{
var itemToTrack:Block;
for(var i:uint = 0; i < itemsToAnimate.length; i++)
{
itemToTrack = itemsToAnimate[i];
itemToTrack.x -= 3;
if(itemToTrack.x < -50)
{
itemsToAnimate.splice(i, 1);
this.removeChild(itemToTrack);
}
}
}
private function createItems():void
{
if(Math.random() > 0.75)
{
var itemToTrack:Block = new Block();
itemToTrack.x = stage.stageWidth - 50;
itemToTrack.y = int( Math.random() * stage.stageHeight)
this.addChild(itemToTrack);
itemsToAnimate.push(itemToTrack);
}
}
and that gets me a random positioning blocks like in the picture
I think you could do something like this (writing it from my head without testing, I hope it will run ok):
function draw(min:Number, max:Number, horSpacing:Number, vertSpacing:Number):void {
var increasing:Boolean = true;
var lastY:Number = min + vertSpacing;
for(var i:int=0; i<100; i++) {
var c:Circle = new Circle(); //where Circle would be your dot with registration point in center
c.x = 20 + i * horSpacing; //hardcoded margin
c.y = (increasing) ? lastY - vertSpacing : lastY + vertSpacing;
lastY = c.y;
addChild(c);
if(c.y <= max) increasing = false;
if(c.y >= min) increasing = true;
}
}
draw(stage.stageHeight - 100, 100, 20, 20);
What you have here is a value that will constantly increase along the x axis and then another that will either be increasing or decreasing along the y axis, alternating when you touch the top or bottom. That's as simple as:
var increaseY:Boolean = true; // Whether we are moving up or down the y axis.
var position:Point = new Point(); // Position to place next item.
var move:int = 10; // How much we move along each axis.
var margin:int = 100; // Distance from top or bottom before alternating.
for each(var i:Sprite in itemsToAnimate)
{
i.x = position.x;
i.y = position.y;
if(increaseY) position.y += move;
else position.y -= move;
position.x += move;
if(position.y < margin || position.y > stage.stageHeight - margin)
{
// Reverse direction.
increaseY = !increaseY;
}
}
move can be adjusted to change the distance between each item along the path.

How to have an object hover back and forth constrained within a specific radius?

I have a sprite in a movie symbol that I would like to hover back and forth within a 360 radius. I was hoping to make it smooth and random. Never really venturing from its original xy cordinates.
I've tried to create some stipulations with if statements and a starting momentum. Like this:
var num = 2;
stage.addEventListener(Event.ENTER_FRAME, hover);
function hover(evt:Event):void{
//start it moving
cloudWhite.y += num;
cloudWhite.x += num;
//declare these variables
var cX = cloudWhite.x;
var cY = cloudWhite.y;
// object travels 10 pixels
var cXP = cX + 10;
var cXN = cX - 10;
var cYP = cY + 10;
var cYN = cY - 10;
// if object goes 10 pixels reverse direction of momentum (maybe)
if (cX >= cXP) {
num = -2;
}
if (cX <= cXN){
num = 2;
}
if (cY >= cYP) {
num = 2;
}
if (cY <= cYN){
num = 2;
}
Clearly this is super wrong because when it runs the object just either goes to 0,0 or to some place that only the math gods know of.
I am clearly a noob at this kind of math so i apologize but I am very excited to learn the trig behind this.
Thank you for your help and thank you for reading.
You are setting all your variables inside the ENTER_FRAME loop, so none of your conditions ever evaluates to true. On every single frame you are doing this:
cloudWhite.x += 2;
cX = cloudWhite.x;
cXP = cX + 10; // Must == cloudWhite's previous x + 10 + 2;
cXN = cX - 10; // Must == cloudWite's previous x -10 + 2;
if(cX > cXP)... // Can never be true.
if(cX < cXN)... // Can never be true.
What you need to do is:
1) Store the original position of cloudWhite somewhere outside the loop, and store it before the loop begins.
2) Define your bounds relative to the original position of cloudWhite, again before your loop begins. Also define the amount you are going to change the position with each iteration.
3) Start your loop.
4) Increment the current position of cloudWhite on each iteration. Add a little random in here if you want the shape to move in a random manner.
5) Check if the new position of cW is outside your bounds and adjust the direction if it is.
The sample below is crude and jerky but I don't know exactly what effect you're looking for. If you want smoother, longer movements in each direction, consider using the Tween class or a Tween library such as the popular Greensock one, instead of incrementing / decrementing the position manually. There's a useful discussion of this here: http://www.actionscript.org/forums/archive/index.php3/t-163836.html
import flash.display.MovieClip;
import flash.events.Event;
// Set up your variables
var original_x:Number = 100; // Original x
var original_y:Number = 100; // Original y
var x_inc:Number = 5; // X Movement
var y_inc:Number = 5; // Y Movenent
var bounds:Number = 50; // Distance from origin allowed
// Doesn't take into account width of object so is distance to nearest point.
// Create an MC to show the bounds:
var display:MovieClip = addChild(new MovieClip()) as MovieClip;
display.graphics.lineStyle(1, 0x0000FF);
display.graphics.beginFill(0x0000FF, 0.5);
display.graphics.drawRect(0-bounds, 0-bounds, bounds * 2, bounds *2);
display.x = original_x;
display.y = original_y;
addChild(display);
// Create our moving mc:
var mc:MovieClip = addChild(new MovieClip()) as MovieClip;
mc.graphics.beginFill(0xFF0000, 1);
mc.graphics.drawCircle(-10, -10, 20);
// Position it:
mc.x = original_x;
mc.y = original_y;
addChild(mc);
// Loop:
function iterate($e:Event = null):void
{
// Move the mc by a random amount related to x/y inc
mc.x += (Math.random() * (2 * x_inc))/2;
mc.y += (Math.random() * (2 * y_inc))/2;
// If the distance from the origin is greater than bounds:
if((Math.abs(mc.x - original_x)) > bounds)
{
// Reverse the direction of travel:
x_inc == 5 ? x_inc = -5 : x_inc = 5;
}
// Ditto on the y axis:
if((Math.abs(mc.y - original_y)) > bounds)
{
y_inc == 5 ? y_inc = -5 : y_inc = 5;
}
}
// Start the loop:
addEventListener(Event.ENTER_FRAME, iterate);
This should get you started. I'm sure there are any number of other ways to do this with formal trig, but this has the benefit of being very simple, and just an extension of your existing method.

AS3 pixel perfect drawing?

When I'm use:
var shape:Shape = new new Shape();
shape.graphics.lineStyle(2,0);
shape.graphics.lineTo(10,10);
addChild(shape);
I get the black line I want, but I also get grey pixels floating around next to them. Is there a way to turn off whatever smoothing/anti-aliasing is adding the fuzzy pixels?
Yes, it is possible to draw pixel-perfect shapes, even with anti-aliasing on. Pixel-hinting is a must. The other half of the equation is to actually issue the drawing commands with whole-pixel coordinates.
For example, you can draw a pixel-perfectly-symmetrical rounded-rectangle with 4px radius curves with the following code. Pay careful attention to what the code is doing, particularly how the offsets relate to the border thickness.
First, keep in mind that when you're drawing filled shapes, the rasterization occurs up to, but no including the right/lower edges of the outline. So to draw a 4x4 pixel filled square, you can just call drawRect(0,0,4,4). That covers pixels 0,1,2,3,4 (5 pixels), but since it doesn't rasterize the right and lower edges, it ends up being 4 pixels. On the other hand, if you're drawing just the outline (without filling it), then you need to call drawRect(0,0,3,3), which will cover pixels 0,1,2,3, which is 4 pixels. So you actually need slightly different dimensions for the fill vs the outline to get pixel-perfect sizes.
Suppose you wanted to draw a button that's 50px wide, 20px tall, with a 4px radius on its rounded edges, which are 2px thick. In order to ensure that exactly 50x20 pixels are covered, and the outside edge of the 2px thick line buts up against the edge pixels without overflowing, you have to issue the drawing command exactly like this. You must use pixel hinting, and you must offset the rectangle by 1px inward on all sides (not half a pixel, but exactly 1). That places the center of the line exactly between pixels 0 and 1, such that it ends up drawing the 2px wide line through pixels 0 and 1.
Here is an example method that you can use:
public class GraphicsUtils
{
public static function drawFilledRoundRect( g:Graphics, x:Number, y:Number, width:Number, height:Number, ellipseWidth:Number = 0, ellipseHeight:Number = 0, fillcolor:Number = 0xFFFFFF, fillalpha:Number = 1, thickness:Number = 0, color:Number = 0, alpha:Number = 1, pixelHinting:Boolean = false, scaleMode:String = "normal", caps:String = null, joints:String = null, miterLimit:Number = 3 )
{
if (!isNaN( fillcolor))
{
g.beginFill( fillcolor, fillalpha );
g.drawRoundRect( x, y, width, height, ellipseWidth, ellipseHeight );
g.endFill();
}
if (!isNaN(color))
{
g.lineStyle( thickness, color, alpha, pixelHinting, scaleMode, caps, joints, miterLimit );
g.drawRoundRect( x, y, width, height, ellipseWidth, ellipseHeight );
}
}
}
Which you'd want to call like this:
var x:Number = 0;
var y:Number = 0;
var width:Number = 50;
var height:Number = 20;
var pixelHinting:Boolean = true;
var cornerRadius:Number = 4;
var fillColor:Number = 0xffffff; //white
var fillAlpha:Number = 1;
var borderColor:Number = 0x000000; //black
var borderAlpha:Number = 1;
var borderThickness:Number = 2;
GraphicsUtils.drawFilledRoundRect( graphics, x + (borderThickness / 2), y + (borderThickness / 2), width - borderThickness, height - borderThickness, cornerRadius * 2, cornerRadius * 2, fillColor, fillAlpha, borderThickness, borderColor, borderAlpha, pixelHinting );
That will produce a pixel-perfectly-symmetrical 2px thick filled rounded rectangle that covers exactly a 50x20 pixel region.
Its very important to notice that using a borderThickness of zero is somewhat non-sensical, and will result in an rectangle oversized by 1 pixel, because it's still drawing a one-pixel wide line, but it's failing to subtract the width (since its zero), hence you'll get an oversized rectangle.
In summary, use the algorithm above, where you add half the border thickness to the x and y coordinates, and subtract the whole border thickness from the width and height, and always use a minimum thickness of 1. That will always result in a rectangle with a border that occupies and does not overflow a pixel region equivalent to the given width and height.
If you want to see it in action, just copy and paste the following code block into a new AS3 Flash Project on the main timeline and run it, as is, since it includes everything necessary to run:
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.events.Event;
import flash.utils.getTimer;
import flash.display.Sprite;
import flash.display.Graphics;
stage.scaleMode = flash.display.StageScaleMode.NO_SCALE;
stage.align = flash.display.StageAlign.TOP_LEFT;
stage.frameRate = 60;
draw();
function draw():void
{
var x:Number = 10;
var y:Number = 10;
var width:Number = 50;
var height:Number = 20;
var pixelHinting:Boolean = true;
var cornerRadius:Number = 4;
var fillColor:Number = 0xffffff; //white
var fillAlpha:Number = 1;
var borderColor:Number = 0x000000; //black
var borderAlpha:Number = 1;
var borderThickness:Number = 2;
var base:Number = 1.6;
var squares:int = 10;
var rows = 4;
var thicknessSteps:Number = 16;
var thicknessFactor:Number = 4;
var offset:Number;
var maxBlockSize:Number = int(Math.pow( base, squares ));
var globalOffset:Number = maxBlockSize; //leave room on left for animation
var totalSize:Number = powerFactorial( base, squares );
var colors:Array = new Array();
for (i = 1; i <= squares; i++)
colors.push( Math.random() * Math.pow( 2, 24 ) );
for (var j:int = 0; j < thicknessSteps; j++)
{
var cycle:Number = int(j / rows);
var subCycle:Number = j % rows;
offset = cycle * totalSize;
y = subCycle * maxBlockSize;
borderThickness = (j + 1) * thicknessFactor;
for (var i:int = 0; i < squares; i++)
{
cornerRadius = Math.max( 8, borderThickness );
borderColor = colors[i];
x = globalOffset + offset + powerFactorial( base, i ); //int(Math.pow( base, i - 1 ));
width = int(Math.pow( base, i + 1 ));
height = width;
if (borderThickness * 2 > width) //don't draw if border is larger than area
continue;
drawFilledRoundRect( graphics, x + (borderThickness / 2), y + (borderThickness / 2), width - borderThickness, height - borderThickness, cornerRadius * 2, cornerRadius * 2, fillColor, fillAlpha, borderThickness, borderColor, borderAlpha, pixelHinting );
}
}
var start:uint = flash.utils.getTimer();
var duration:uint = 5000;
var sprite:Sprite = new Sprite();
addChild( sprite );
var gs:Graphics = sprite.graphics;
addEventListener( flash.events.Event.ENTER_FRAME,
function ( e:Event ):void
{
var t:uint = (getTimer() - start) % duration;
if (t > (duration / 2))
borderThickness = ((duration-t) / (duration/2)) * thicknessSteps * thicknessFactor;
else
borderThickness = (t / (duration/2)) * thicknessSteps * thicknessFactor;
//borderThickness = int(borderThickness);
cornerRadius = Math.max( 8, borderThickness );
borderColor = colors[squares - 1];
x = 0;
y = 0;
width = int(Math.pow( base, squares ));
height = width;
if (borderThickness * 2 > width) //don't draw if border is larger than area
return;
gs.clear();
drawFilledRoundRect( gs, x + (borderThickness / 2), y + (borderThickness / 2), width - borderThickness, height - borderThickness, cornerRadius * 2, cornerRadius * 2, fillColor, fillAlpha, borderThickness, borderColor, borderAlpha, pixelHinting );
}, false, 0, true );
}
function powerFactorial( base:Number, i:int ):Number
{
var result:Number = 0;
for (var c:int = 0; c < i; c++)
{
result += int(Math.pow( base, c + 1 ));
}
return result;
}
function drawFilledRoundRect( g:Graphics, x:Number, y:Number, width:Number, height:Number, ellipseWidth:Number = 0, ellipseHeight:Number = 0, fillcolor:Number = 0xFFFFFF, fillalpha:Number = 1, thickness:Number = 0, color:Number = 0, alpha:Number = 1, pixelHinting:Boolean = false, scaleMode:String = "normal", caps:String = null, joints:String = null, miterLimit:Number = 3 )
{
if (!isNaN( fillcolor))
{
g.beginFill( fillcolor, fillalpha );
g.drawRoundRect( x, y, width, height, ellipseWidth, ellipseHeight );
g.endFill();
}
if (!isNaN(color))
{
g.lineStyle( thickness, color, alpha, pixelHinting, scaleMode, caps, joints, miterLimit );
g.drawRoundRect( x, y, width, height, ellipseWidth, ellipseHeight );
}
}
Try turning on pixelHinting:
shape.graphics.lineStyle(2, 0, 1, true);
More about pixelHinting here.
You can't turn off antialiasing completely. If you want a sharp, pixelated line then unfortunately you have to draw pixel by pixel, using a Bitmap and setPixel()

Drawing an honeycomb with as3

I'm trying to create an honeycomb with as3 but I have some problem on cells positioning.
I've already created the cells (not with code) and for cycled them to a funcion and send to it the parameters which what I thought was need (the honeycomb cell is allready on a sprite container in the center of the stage).
to see the structure of the cycle and which parameters passes, please see the example below, the only thing i calculate in placeCell is the angle which I should obtain directly inside tha called function
alt text http://img293.imageshack.us/img293/1064/honeycomb.png
Note: the angle is reversed but it isn't important, and the color are useful in example only for visually divide cases.
My for cycle calls placeCell and passes cell, current_case, counter (index) and the honeycomb cell_lv (cell level).
I thought it was what i needed but I'm not skilled in geometry and trigonometry, so I don't know how to position cells correctly:
import flash.display.Sprite;
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
function createHoneycomb (cells:int):void {
var honeycomb:Sprite = new Sprite ();
addChild (honeycomb);
var cell_lv:int = 1;
var increment:int = 6;
var tot_cur_cells:int = 1;
var current_case:int = 0;
var case_counter:int = 1;
var case_length:int = 1;
var max_cases:int = 6;
var nucleus:Sprite = new cell (); // hexagon from library
honeycomb.addChild (nucleus);
for (var i:int = 1; i <= cells; i ++) {
if (case_counter < case_length) {
case_counter ++;
} else {
current_case ++;
if (current_case > max_cases) current_case = 1;
case_counter = 1;
}
if (i == tot_cur_cells) { // if i reach the current level
if (i > 1) cell_lv ++;
case_length = cell_lv;
tot_cur_cells += (increment * cell_lv);
}
var current_cell:Sprite = new cell (); // hexagon from library
honeycomb.addChild (current_cell);
placeCell (current_cell, case_counter, current_case, cell_lv);
}
function centerHoneycomb (e:Event):void {
honeycomb.x = stage.stageWidth / 2
honeycomb.y = Math.round (stage.stageHeight / 2);
}
stage.addEventListener (Event.RESIZE, centerHoneycomb)
stage.dispatchEvent (new Event (Event.RESIZE));
}
function placeCell (cell:Sprite, counter:int, current_case:int, cell_lv:int):void {
var margin:int = 2;
// THIS IS MY PROBLEM
var start_degree:Number = (360 / (cell_lv * 6));
var angle:Number = (start_degree * ((current_case - 1) + counter) - start_degree);
var radius:Number = (cell.width + margin) * cell_lv;
cell.x = radius * Math.cos (angle);
cell.y = radius * Math.sin (angle);
// end of the problem
if (angle != 0) trace ("LV " + cell_lv + " current_case " + current_case + " counter " + counter + " angle " + angle + " radius " + radius);
else trace ("LV " + cell_lv + " current_case " + current_case + " counter " + counter + " angle " + angle + " radius " + radius);
}
createHoneycomb (64);
if you copy and paste this code, it works but you need to create an hexagon and call it in the actionscript library as cell
how can I do to solve it?
I've also thought to use a switch with the cases to align it, but i think is a little bit buggy doing this
Okay, I really loved this question. It was interesting, and challenging, and I got a working result. I didn’t use any of your code as the base though, but started from scratch, so depending on your final use, you might need to change a bit.
I did however created similar variables to those inside of your cells (in the picture). For each cell you have the following properties:
the iterating variable i is equally to your cell number
the radius r equals your level, and expresses the distance from the center (with 0 being the center)
the position p expresses the position in the current radius
the sector s equals your case, but starts with zero
p % r equals your index
I don’t have an angle, simply because I don’t position the individual hexagons using an angle. Instead I base the position of the (fixed) positions of the hexagons at radius 1 and calculate the missing ones in between.
The following code shows my implementation with 61 (60 + the center; but it’s configurable). You can also see the code in action on Wonderfl.
package
{
import flash.display.Sprite;
public class Comb extends Sprite
{
public function Comb ()
{
Hexagon.scale = 0.5;
this.x = stage.stageWidth / 2;
this.y = stage.stageHeight / 2;
// draw honeycomb with 60 cells
drawComb( 60 );
}
private function drawComb ( n:uint ):void
{
var colors:Array = new Array( 0x33CC33, 0x006699, 0xCC3300, 0x663399, 0xFF9900, 0x336666 );
var sectors:Array = new Array(
new Array( 2, 0 ),
new Array( 1, 1 ),
new Array( -1, 1 ),
new Array( -2, 0 ),
new Array( -1, -1 ),
new Array( 1, -1 ) );
var w:Number = 0.50 * Hexagon.hxWidth;
var h:Number = 0.75 * Hexagon.hxHeight;
var r:uint, p:uint, s:uint;
var hx:Hexagon;
for ( var i:uint = 0; i <= n; i++ )
{
r = getRadius( i );
p = getPosition( i, r );
s = getSector( i, r, p );
// create hexagon
if ( r == 0 )
hx = new Hexagon( 0xCCCCCC );
else
hx = new Hexagon( colors[s] );
hx.x = w * ( r * sectors[s][0] - ( p % r ) * ( sectors[s][0] - sectors[ ( s + 1 ) % 6 ][0] ) );
hx.y = h * ( r * sectors[s][1] - ( p % r ) * ( sectors[s][1] - sectors[ ( s + 1 ) % 6 ][1] ) );
addChild( hx );
}
}
private function getRadius ( i:uint ):uint
{
var r:uint = 0;
while ( i > r * 6 )
i -= r++ * 6;
return r;
}
private function getPosition ( i:uint, r:uint ):uint
{
if ( r == 0 )
return i;
while ( r-- > 0 )
i -= r * 6;
return i - 1;
}
private function getSector ( i:uint, r:uint, s:uint ):uint
{
return Math.floor( s / r );
}
}
}
import flash.display.Shape;
class Hexagon extends Shape
{
public static var hxWidth:Number = 90;
public static var hxHeight:Number = 100;
private static var _scale:Number = 1;
public function Hexagon ( color:uint )
{
graphics.beginFill( color );
graphics.lineStyle( 3, 0xFFFFFF );
graphics.moveTo( 0, -50 );
graphics.lineTo( 45, -25 );
graphics.lineTo( 45, 25 );
graphics.lineTo( 0, 50 ),
graphics.lineTo( -45, 25 );
graphics.lineTo( -45, -25 );
graphics.lineTo( 0, -50 );
this.scaleX = this.scaleY = _scale;
}
public static function set scale ( value:Number ):void
{
_scale = value;
hxWidth = value * 90;
hxHeight = value * 100;
}
public static function get scale ():Number
{
return _scale;
}
}