Browse the notebook

Tag: flash

Isometric to Cartesian

var centerX:Number=stage.stageWidth/2;
var centerY:Number=stage.stageHeight/2;
// 1 to 2 ratio
// try others 1 / 1.5 etc...
var theta:Number = Math.atan(1 / 2);
 
var cosX:Number=Math.cos(theta);
var sinX:Number=Math.sin(theta);
var pnt:Point = new Point();

function iso3D(x:Number, y:Number, z:Number):Point {
	pnt.x = centerX + (x-z) *  cosX;
	pnt.y = centerY -  (x+z) * sinX - y;
	return pnt;
}

var p:Point = iso3D(0,0,0);

graphics.beginFill(0x000000);
graphics.drawCircle(p.x, p.y, 2);

// x axis positive
trace("x = red");
for (var i:int = 1; i<10; i++){
	graphics.beginFill(0xFF0000);
	p = iso3D(i*10, 0, 0);
	graphics.drawCircle(p.x, p.y, 2);
}

// y axis positive
trace("y = green");
for (i= 1; i<10; i++){
	graphics.beginFill(0x00FF00);
	p = iso3D(0, i * 10, 0);
	graphics.drawCircle(p.x, p.y, 2);
}

// z axis positive
trace("z = blue");
for (i= 1; i<10; i++){
	graphics.beginFill(0x0000FF);
	p = iso3D(0, 0, i * 10);
	graphics.drawCircle(p.x, p.y, 2);
}

The above code demos a conversion from isometric coordinates to cartesian coordinates. It draws out part of the x, y and z axis using the iso3D() function.

I’ve always faked isometric conversion by just tweaking numbers. A few years ago I created some strange isometric engines (here’s another example ). The other day when I wrote the isometric voxels snippet I just created the iso3D() function with a little trial and error. As you’ll see it’s not exactly the same as the one here. This new conversion is the result of some googling. The updated conversion is pretty close to the one that I wrote for the voxel post, but has one less multiplication… and a clearer place to control the scale ratio …

Read snippet: Isometric to Cartesian

Matrix.transformPoint()

var circle:Shape = Shape(addChild(new Shape()));
with(circle.graphics) beginFill(0x00000), drawCircle(0,0,10);

var point:Point = new Point();
var trans:Matrix = new Matrix();
trans.rotate(Math.PI);
trans.scale(.5, .5);
trans.tx = stage.stageWidth / 2;
trans.ty = stage.stageHeight / 2;

addEventListener(Event.ENTER_FRAME, onLoop);

function onLoop(evt:Event):void {
	point.x = mouseX - trans.tx;
	point.y = mouseY - trans.ty;
	
	point = trans.transformPoint(point);
	
	circle.x = point.x;
	circle.y = point.y;
}

If you don’t feel like rolling your own transformations Matrix.transformPoint() is a very powerful method. It simply applies the tranformations of a given matrix to a Point. The above example scales rotates and translates a point which is then used to position a circle Shape.

Matrix.transformPoint() is well suited for creating orbiting behavior:

var circle:Shape = Shape(addChild(new Shape()));
with(circle.graphics) beginFill(0x00000), drawCircle(0,0,10);

var point:Point = new Point(100,0);
var trans:Matrix = new Matrix();
 trans.rotate(.1);
 trans.scale(.99,.99);

addEventListener(Event.ENTER_FRAME, onLoop);

function onLoop(evt:Event):void {
	 
      point = trans.transformPoint(point);
	 
      circle.x = point.x + stage.stageWidth / 2;
      circle.y = point.y + stage.stageHeight / 2;
}

This code will cause the circle Shape to move in a spiral formation.

Read snippet: Matrix.transformPoint()

BitmapData.floodFill()

var canvas:BitmapData = new BitmapData(400,400,false, 0xCC0000);
addChild(new Bitmap(canvas));

var s:Shape = new Shape();
s.graphics.beginFill(0x00CCCC);
s.graphics.moveTo(Math.random()*400,Math.random()*400);
for(var i:int = 0; i<10; i++){
	s.graphics.lineTo(Math.random()*400,Math.random()*400);
}
canvas.draw(s);

stage.addEventListener(MouseEvent.CLICK, onDown);
function onDown(evt:MouseEvent):void {
	canvas.floodFill(mouseX, mouseY, 0x000000);
}

floodFill() is basically the paint bucket (fill) tool in any bitmap drawing program. The above example draws an arbitrary blue polygon to a red background. Click anywhere on the resulting image to see floodFill() in action.

floodFill() takes 3 arguments… x, y and color.

Read snippet: BitmapData.floodFill()

E4X and ActionScript Variables

var backgroundColor:uint = 0xEFEFEF;
var borderColor:uint = 0xFF0000;
var buttonOverColor:uint = 0x0000FF;
var buttonOutColor:uint = 0x00CCCC;

var uiColors:XML = <ui>
	<default color="0xCCCCCC" />
	<background color = { backgroundColor } />
	
	<!-- note hexidecimal formatting code -->
	<border color={ ("0x" + borderColor.toString(16)) } />
	
	<button overColor={ buttonOverColor} outColor={ buttonOutColor } />
</ui>

trace(uiColors.toXMLString());

/*outputs:
<ui>
  <default color="0xCCCCCC"/>
  <background color="15724527"/>
  <border color="0xff0000"/>
  <button overColor="255" outColor="52428"/>
</ui>
*/

The first time I needed to use an ActionScript variable within inline XML I was stumped. I couldn’t figure it out and I wasn’t able to easily find it on google. I eventually found it somewhere (don’t remember where… possibly hidden away in the docs).

Now a search for “insert actionscript variables into e4x” on google gives plenty of results. But I figure it’s worth a post.

I use actionscript to generate XML all the time so this comes in handy. I also store color values in automatically generated XML all the time. If I’m feeling organized I’ll use something like what you see on line 10:

<border color={ ("0x" + borderColor.toString(16)) } />

If you look at the output you’ll see this formats the uint so that it’s readable as a hex number. By default (as you can see in the output) uints will show up in decimal notation. This really doesn’t make any difference if you don’t care about XML readability … or if you just don’t care about the readability of the colors stored in your XML…..

Read snippet: E4X and ActionScript Variables

E4X Filtering

var userInfo:XML = <users>
  <user fname="joe" lname="smith" age="31" />
  <user fname="mildred" lname="calder" age="64" />
  <user fname="ben" lname="nathanson" age="20" />
  <user fname="james" lname="biuford" age="19" />
  <user fname="nick" lname="calhoun" age="45" />
</users>;


trace("Users over 20:n");
trace(userInfo.user.(@age > 20).toXMLString());

trace("nUsers with the name nick:n");
trace(userInfo.user.(@fname == "nick" ).toXMLString());

// use regular expressions with e4x
trace("nUsers with name starting with j:n");
trace(userInfo.user.(/^j/.test(@fname)));

/*
outputs:

Users over 20:

<user fname="joe" lname="smith" age="31"/>
<user fname="mildred" lname="calder" age="64"/>
<user fname="nick" lname="calhoun" age="45"/>

Users with the name nick:

<user fname="nick" lname="calhoun" age="45"/>

Users with name starting with j:

<user fname="joe" lname="smith" age="31"/>
<user fname="james" lname="biuford" age="19"/>

*/

One of the nicest features of E4X is filtering. The above code shows a few simple examples … the last example makes use of regular expressions — I first read using regular expressions and E4X somewhere on http://www.darronschall.com/.

I usually prefer to use a database for any kind of info I’ll be searching… but if you know you have a relatively small amount of data XML can be a fine way to go.

Read snippet: E4X Filtering

Isometric Voxels

// isometric conversion
var centerX:Number=stage.stageWidth/2;
var centerY:Number=stage.stageHeight/2;
var theta:Number=Math.PI/4;// 45 degrees;
var cosX:Number=Math.cos(theta);
var sinX:Number=Math.sin(theta);
var pnt:Point = new Point();
function iso3D(x:Number, y:Number, z:Number):Point {
	pnt.x = centerX + (x-z) *  cosX
	pnt.y = centerY -  (x+z) * 0.5 * sinX - y;
	return pnt;
}
// example:
var canvas:BitmapData=new BitmapData(stage.stageWidth,stage.stageHeight,true,0xFF000000);
addChild(new Bitmap(canvas,"auto",true));
var size:int=100;
var hs:int=size / 2;
var pen:Point = new Point();
var vect:Vector3D = new Vector3D();
// draw a few shapes with offset:
for (var dist:int = 10; dist <= 80; dist *= 2) {
	// voxel space:
	for (var i:int = 0; i<size; i++) {
		for (var j:int = 0; j<size; j++) {
			for (var k:int = 0; k<size; k++) {
				vect.x=j-hs;
				vect.y=i-hs;
				vect.z=k-hs;
				pen = iso3D(vect.x,vect.y,vect.z);
				if (Math.sqrt((vect.x * vect.x) + (vect.y * vect.y) + (vect.z * vect.z)) <dist) {
					// using Vector3D.distance() is very slow compared to above
					// a few types of coloring:
					var xp:Number = pen.x + (dist <<2) - 200;
					canvas.setPixel(xp, pen.y-100, (i <<16 | j <<8 | k) <<1);
					canvas.setPixel(xp, pen.y+100, (k <<16 | k <<8 | k+j)  );
				}
			}
		}
	}
}

The above will draw this:

You can read more about voxels here.

This isn’t the speediest way to do voxels (especially if you want to animate). This was just the first thing that came to mind.

Read snippet: Isometric Voxels

Blendmode Emboss

var canvas:BitmapData = new BitmapData(500, 500, true, 0xFFFFFFFF);
var color:BitmapData= new BitmapData(500, 500, true, 0x81666666);
var over:BitmapData = new BitmapData(500, 500, true, 0xFF000000);
addChild(new Bitmap(canvas, "auto", true));
var circle:Shape = new Shape();
circle.graphics.beginFill(0xFFFFFF,1);
circle.graphics.drawCircle(0,0,50);
var m:Matrix = new Matrix();
m.tx = 0;
m.ty = 1;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	circle.x = mouseX;
	circle.y = mouseY;
	canvas.draw(circle, circle.transform.matrix);
	canvas.copyPixels(color, color.rect, new Point(0,0), null, null, true);
	over.copyPixels(canvas, canvas.rect, new Point(0,0), null, null, true);
	canvas.draw(over, m, null, BlendMode.SCREEN);
	over.applyFilter(over, over.rect, new Point(-2,-2), new BlurFilter(10,10,1));
	canvas.draw(over, m, null, BlendMode.SUBTRACT);
}

Grayscale emboss technique. More info here.

Read snippet: Blendmode Emboss

Dynamic Vars Dictionary


var vars:Dictionary = new Dictionary();

var sp:Sprite = new Sprite();

// associate variables with a sprite (or any non-dynamic class)
vars[sp] = {posX:100, posY:100, velX:1, velY:1};

// read
trace(vars[sp].posX);

I’ve heard people mention that they wish the sprite class were dynamic… meaning they wish they could add methods and properties to a Sprite instance at runtime. There’s no way I know of to do this, however… the dictionary class can be used to associate variables with any non-dynamic class instance… as it does in this the above example.

The dictionary class is similar to an associative array except that instead of using strings for keys, dictionaries use object instances.

Read snippet: Dynamic Vars Dictionary

Transparent copyPixels()

var canvas:BitmapData=new BitmapData(400,400,true,0x000000);
var eraser:BitmapData=new BitmapData(400,400,true,0x00000000);
addChild(new Bitmap(canvas));
var redOval:Shape = new Shape();
with(redOval.graphics) lineStyle(0,0), beginFill(0xFF0000), drawEllipse(0,0,10,50);

// draw a background to emphasize transparency 
createBackground();

addEventListener(Event.ENTER_FRAME, onLoop);

function onLoop(evt:Event):void {
	// clear canvas so that it is completely transparent
	canvas.copyPixels(eraser, eraser.rect, new Point(0,0), eraser);
	redOval.x = mouseX;
	redOval.y = mouseY;
	redOval.rotation += 10
	// transform.matrix contains all transformation information for
	// the redOval including scaleX, scaleY, x, y, rotation etc...
	canvas.draw(redOval, redOval.transform.matrix);
}

function createBackground():void {
	for (var i:int = 0; i<100; i++){
		with(graphics) lineStyle(0,0x000000), lineTo(Math.random()*400, Math.random()*400);
	}
}

This example builds on yesterdays snippet. Instead of just allowing the red oval to be continuously drawn to the canvas BitmapData… in this example the canvas BitmapData is erased again and again before the red oval is drawn to it. To erase it with a flat color you might use BitmapData.fillRect() but if you want to erase it so that it is completely transparent you need to use BitmapData.copyPixels():

canvas.copyPixels(eraser, eraser.rect, new Point(0,0), eraser);

The eraser BitmapData is a completely transparent BitmapData object. The key here is the fourth argument…. “alphaBitmapData”.This is what causes the canvas BitmapData to become completely transparent again at the beginning of each enterFrame.

This argument is separate from the first argument (sourceBitmapData) for added flexibility.

Read snippet: Transparent copyPixels()

BitmapData Brush

var canvas:BitmapData=new BitmapData(400,400,true,0xFFCCCCCC);
addChild(new Bitmap(canvas));

var redOval:Shape = new Shape();
with(redOval.graphics) lineStyle(0,0), beginFill(0xFF0000), drawEllipse(0,0,10,50);

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {

	redOval.x = mouseX;
	redOval.y = mouseY;
	redOval.rotation += 10
	// transform.matrix contains all transformation information for 
	// the redOval including scaleX, scaleY, x, y, rotation etc...
	canvas.draw(redOval, redOval.transform.matrix);
}

A very easy way to create a BitmapData brush.

Read snippet: BitmapData Brush