Browse the notebook

Tag: flash

perlinNoise()

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

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
  canvas.perlinNoise(200,200, 2, 1, true, false,0, true, 
                              [new Point(mouseX, mouseY),
                              new Point(-mouseX, -mouseY)]);
																				    
}

There area few snippets on the way that involve perlin noise. Starting here with something simple. This creates 2 octave perlin noise and moves each octave based on the mouse location.

Perlin noise was invented by Ken Perlin.

Read snippet: perlinNoise()

drawPath() Circle Segment

drawPath() is flash 10 player only

[SWF(width=400,height=400,backgroundColor=0xEFEFEF,frameRate=30)]

const TWO_PI:Number = Math.PI * 2;

var resolution:Number = 50;
var step:Number = TWO_PI / resolution;
var maxIndex:int = 0;

var coords:Vector.<Number> = new Vector.<Number>();
var drawCommands:Vector.<int> = new Vector.<int>();

// populate vectors
for (var i:Number = 0; i < TWO_PI + step; i += step){
	coords.push(100 * Math.cos(i));
	coords.push(100 * Math.sin(i));
	drawCommands.push(GraphicsPathCommand.LINE_TO);
}
 
var circleSegment:Shape = new Shape();
circleSegment.x = circleSegment.y = 200;
addChild(circleSegment);

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	with (circleSegment.graphics) {
		clear();
		beginFill(0x000000);
		
		// count by two, up to coords.length (drawCommands is exactly half the length of coords)
		maxIndex =  Math.ceil((mouseX / stage.stageWidth)  * drawCommands.length) * 2;

        drawPath(drawCommands, coords.slice(0, maxIndex));
	}
}

The new additions to the Drawing API are great. This is just a quick test done with drawPath() to create a circle segment – this technique could be used to draw a pie chart.

The old way would have required lots of calls to the Graphics.lineTo() method. Take a look:


const TWO_PI:Number = Math.PI * 2;

var resolution:Number = 50;
var step:Number = TWO_PI / resolution;
var maxAngle:Number;

var circleSegment:Shape = new Shape();
circleSegment.x = circleSegment.y = 200;
addChild(circleSegment);

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	with (circleSegment.graphics) {
		clear();
		beginFill(0x000000);
		
		// count up to (TWO_PI + step), we add step to close the circle
		maxAngle =  (TWO_PI + step) *  (mouseX / stage.stageWidth);

		for (var i:Number = 0; i < maxAngle; i += step) {
			var xp:Number = 100 * Math.cos(i);
			var yp:Number = 100 * Math.sin(i);
			lineTo(xp, yp);
		}
	}
}

If your interested in learning more about the FP10 Drawing API features, you can read more here.

Read snippet: drawPath() Circle Segment

Isometric Box

stage.frameRate = 30;

for (var i:int = 0; i<100; i++){
    makeBoxSegment(200, 200 - i, i * 2);
}

function makeBoxSegment(xp:Number, yp:Number, col:uint):Sprite {
	var isoBox:Sprite = Sprite(addChild(new Sprite()));
	with (isoBox) scaleY = .5, y = yp, x = xp;
	var box:Shape = Shape(isoBox.addChild(new Shape()));
	box.rotation = 45;
	with (box.graphics) beginFill(col), drawRect(-50,-50,100,100);
	isoBox.addEventListener(Event.ENTER_FRAME, onRotate);
	return isoBox;
}

function onRotate(evt:Event):void {
	evt.currentTarget.getChildAt(0).rotation = mouseX;
}

An isometric box that rotates with the mouseX.

Read snippet: Isometric Box

Multiple Keys

var key:Object = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
function onKeyPressed(evt:KeyboardEvent):void {
	key[evt.keyCode] = true;
	key.keyCode = evt.keyCode;
}
function onKeyReleased(evt:KeyboardEvent):void {
	key[evt.keyCode] = false
}

// example

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	
	//trace(key.keyCode);
	 
	if (key[Keyboard.LEFT]){
		trace("left");
	}
	
	if (key[Keyboard.RIGHT]){
		trace("right");
	}
	
	// keys #1, #2 and #3 are down
	if (key[49] && key[50] && key[51]){
		trace("one two thee");
	}
	
	// keys #6, #7, #8 and #9 keys are down
	if (key[54] && key[55] && key[56] && key[57]){
		trace("six seven eight nine");
	}
}

The first 10 lines of code make up this snippet. This is an easy way to keep track of multiple key presses. For games, this is the only key technique I use … wrapped up in a Singleton.

Read snippet: Multiple Keys

String.replace()

var words:String = "ActionSnippet.com is a website. ActionSnippet.com is a blog.";

// outputs: "ActionSnippet.com is a website. ActionSnippet.com is a blog.";
trace(words);

// the "/g" tells it to replace all instances of ActionSnippet.com
words = words.replace(/ActionSnippet.com/g, "SomeWebsite.com");

// outputs: SomeWebsite.com is a website. SomeWebsite.com is a blog.
trace(words);

Just a quick response to a student question.

Read snippet: String.replace()

Recursive Tree

var branches:int = 0;
var maxBranches:int = 400;
 
graphics.lineStyle(0,0x000000);

makeBranch(300,350,100,-45,45);
	 
function makeBranch(xp:Number, yp:Number, leng:Number, min:Number, max:Number):void {

	var endX:Number, endY:Number;
	var theta:Number = (min + Math.random()*(max-min) - 90) * Math.PI / 180;
	 
	endX = xp + leng * Math.cos(theta);
	endY = yp + leng * Math.sin(theta);

	graphics.moveTo(xp, yp);
	graphics.lineTo(endX, endY);
	
	if (branches < maxBranches) {
		var newLength:Number = leng*.7; 
		setTimeout(makeBranch, 0, endX, endY, newLength, -90, 0);
		setTimeout(makeBranch, 0, endX, endY, newLength, 0, 90);
	}
	branches+=2;
}

Draws a tree using recursion.

Read snippet: Recursive Tree

3D Shape

stage.frameRate = 30;
var centerX:Number = 200, centerY:Number = 200, zpos:Number, xpos:Number, ypos:Number, depth:Number;
var rotX:Number = 0, rotY:Number = 0, px:Number, py:Number, pz:Number;
var cosx:Number, cosy:Number, sinx:Number, siny:Number;

var canvas:BitmapData = new BitmapData(400,400,true,0xFF000000);
addChild(new Bitmap(canvas));
 
addEventListener(Event.ENTER_FRAME, onLoop);
 
function onLoop(evt:Event):void {
	canvas.fillRect(canvas.rect, 0xFF000000);
	 rotX += (mouseX / 50 - rotX)/12;
	 rotY += (mouseY / 50 - rotY)/12;
	 
	 cosx = Math.cos(rotX);
	 cosy = Math.cos(rotY);
	 sinx = Math.sin(rotX);
	 siny = Math.sin(rotY);
	 for (var a:Number =0; a < 6.28; a+=.1){
		  for (var b:Number =0; b < 6.28; b+=.05){
			  px = 100 * Math.cos(a) * Math.cos(b) * Math.cos(b);
			  py = 100 * Math.sin(a) * Math.cos(b) 
			  pz = 100 * Math.sin(b);
			  zpos= pz*cosx - px*sinx  ;
	          xpos= pz*sinx +px*cosx  ;
	          ypos= py*cosy - zpos*siny  ;
	          zpos= py*siny+ zpos*cosy ;
			  depth = 1/((zpos/340)+1);
			  canvas.setPixel((xpos * depth) + centerX, (ypos * depth) + centerY, 0xFFFFFF);
		  }
	 }
}

Renders a rotating 3D shape.

Read snippet: 3D Shape

Simple Particles

stage.frameRate = 30;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void{
	if (int(Math.random()*5)==1){
	  for (var i:int= 0; i<10; i++) createParticle();
	}
}

function createParticle():void{
	var s:MovieClip = new MovieClip();
	s.graphics.beginFill(0);
	s.graphics.drawCircle(0,0,Math.random()*10 + 2);
	s.velX = Math.random()*10-5
	s.velY =  Math.random()*10-5
	s.posX = s.x = 200;
	s.posY = s.y = 200;
	addChild(s);
	s.addEventListener(Event.ENTER_FRAME, onRunParticle);
}

function onRunParticle(evt:Event):void {
	var s:MovieClip = MovieClip(evt.currentTarget);
	s.posX += s.velX;
	s.posY += s.velY;
    s.scaleX = s.scaleY -=  .04;
	if (s.scaleX < 0){
		removeChild(s);
		s.removeEventListener(Event.ENTER_FRAME, onRunParticle);
	}
	s.x = s.posX;
	s.y = s.posY;
}

Nothing special here. But my students are always asking me about this – in class I have them alter this code to make fire, water and abstract particle systems.

Read snippet: Simple Particles

Dynamic Timeline Vars

this.myVar = "I am a dynamic variable";
trace(this.myVar);

// trace(myVar) // will cause an error

This code will add dynamic untyped variables to the timeline. Although this example is pretty useless, it scratches the surface of an interesting topic…. by default all flash timeline code gets compiled into a giant dynamic document class that uses the undocumented addFrameScript() function. This means that all import statements on the timeline, even ones not on frame one become part of this large document class.

Read snippet: Dynamic Timeline Vars

Recursion Trick w/ setTimeout()

var counter:int = 0;

graphics.lineStyle(0,0x000000);

recursive();

function recursive():void{
	
	if (counter < 4000){
	   graphics.moveTo(10,10);
	   graphics.lineTo(counter, 200);
	   counter+=4;
          // don't call recursive(), use setTimeout instead
	   setTimeout(recursive,0);
	}else{
		trace(counter / 4 + " lines were drawn");
	}

Be careful with this one, if you don’t know what your doing you may be able to crash flash.

Anyway… if you use a recursive function in flash you may find yourself getting a stack overflow error. You can avoid this by using setTimeout():

 // don't call recursive(), use setTimeout() instead
setTimeout(recursive,0);

Of course… the stack overflow error is there for a reason, if used incorrectly you could bring the flash player to a standstill.

You can also achieve animated recursion by actually adding a delay to your setTimout() call:

 // don't call recursive(), use setTimeout() instead
setTimeout(recursive,10);
Read snippet: Recursion Trick w/ setTimeout()