22 March 2011

Using Drawing API for orbit-like shapes in AS3

Before reading this post, it would be great if you could take a look at related posts:

- How to orbit in AS3
- Making orbit trails in Flash
- AS3 drawing API examples
- Curves and fills with AS3 drawing API

Let's take a look at the completed code:

import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Graphics;

function orbit(planet:MovieClip, sat:MovieClip, radius:Number, speed:Number,
trailStrength:Number, trailColor:uint):void
{
var currentDegrees:Number = 0;
var trail:MovieClip = new MovieClip();
trail.graphics.lineStyle(trailStrength, trailColor);

var setPosition:Boolean = true;

addChild(trail);

this.addEventListener(Event.ENTER_FRAME, doEveryFrame);

function doEveryFrame(event:Event):void
{
currentDegrees += speed;
var radians:Number = getRadians(currentDegrees);
var posX:Number = planet.x + Math.sin(radians) * radius;
var posY:Number = planet.y + Math.cos(radians) * radius;
sat.x = posX;
sat.y = posY;

// update trail graphics
if (setPosition) {
trail.graphics.moveTo(posX, posY);
setPosition = false;
}
trail.graphics.lineTo(sat.x, sat.y);
}

function getRadians(degrees:Number):Number
{
return degrees * Math.PI / 180;
}
}

orbit(planetMC, satMC, 220, -1, 2, 0xffff00);
orbit(planetMC, satMC2, 120, 4, 2, 0xffff00);
orbit(satMC2, moon, 20, -31, 1, 0xffffff);
orbit(satMC, moon2, 20, 12, 1, 0xffffff);
orbit(satMC, moon3, 50, 4, 1, 0xffffff);


This is part of the result image.



Orbit function is a bit different from same function in How to orbit in AS3 post. First, one more import line is added:

import flash.display.Graphics;

This is needed because we will use drawing properties of display object, in this case - MovieClip.

So, orbit function has two additional parameters: trailStrength and trailColor.

Before event listener we have 4 new lines:

var trail:MovieClip = new MovieClip();
trail.graphics.lineStyle(trailStrength, trailColor);
var setPosition:Boolean = true;
addChild(trail);


First we define new MovieClip and we set lineStyle using our two new parameters. We add that MovieClip to stage using addChild.

Now what is setPosition Boolean value? In this particular example, objects for 'planets' and 'moons' are randomly placed on Stage and when movie starts, drawing begins from those starting position, which is bad because it breaks image symmetry. That's why I use this Boolean value to move 'drawing pen' to right position in first iteration of event listener with:

trail.graphics.moveTo(posX, posY);

After this move, setPosition becomes false and move is never executed again. Only remains to draw new line with:

trail.graphics.lineTo(sat.x, sat.y);

As you can see from code above, orbit function calls now have 6 parameters and last two are trial line width and trail line color.

[DOWNLOAD SOURCE]

Here are few more images created using this technique.



Have some of your own? Let me know.

*_*

0 comments:

 

template by blogger templates