Browse the notebook

Tag: actionscript

Cut Image Into Squares

[SWF(width=650, height=650)]
var loader:Loader = new Loader();
loader.load(new URLRequest("https://actionsnippet.com/wp-content/chair.jpg"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
x = y = 25;
var w:Number;
var h:Number;
var rows:Number = 20;
var cols:Number = 20;
var tiles:Vector.<Sprite> = new Vector.<Sprite>();
function onLoaded(evt:Event):void{
	w = evt.target.width;
	h = evt.target.height;
	var image:BitmapData = Bitmap(evt.target.content).bitmapData;
	var tileWidth:Number = w / cols;
	var tileHeight:Number = h / rows;
	var inc:int = 0;
	var pnt:Point = new Point();
	var rect:Rectangle = new Rectangle(0,0,tileWidth,tileHeight);
	for (var i:int = 0; i<rows; i++){
		for (var j:int = 0; j<cols; j ++){
			 var currTile:BitmapData= new BitmapData(tileWidth, tileHeight, true, 0x00000000);
			 rect.x = j * tileWidth;
			 rect.y = i * tileHeight;
			 currTile.copyPixels(image, rect, pnt, null, null, true);
			 var bit:Bitmap = new Bitmap(currTile, "auto", false); 
			 var s:Sprite = tiles[inc] = Sprite(addChild(new Sprite()));
			 // offset them a little bit to show that they are in fact tiles.
			 s.x = rect.x + Math.random()*10 - 5;
			 s.y = rect.y + Math.random()*10 - 5;
			 
			/* If you have TweenLite, try something like this:
			 s.x = rect.x;
			 s.y = rect.y;
			 TweenLite.from(s, 0.3, {x:Math.random()*stage.stageWidth, y:Math.random()*stage.stageHeight, alpha:0, delay:inc / 50});
			 */
			 s.addChild(bit);
			 inc++;
		}
	}
}

This snippet shows how to cut a dynamically loaded image up into small squares (or rectangles). Each square is placed into a sprite and these sprites are stored in a vector for later use. This kind of thing could be useful in conjunction with tweening engines to create transition effects. If you have TweenLite on your machine you could add the import statement “import gs.TweenLIte” and uncomment lines 33-35.

For the purposes of this demo I just offset each sprite slightly to show that it the loaded image has in face been cut up. Here are a few stills with created by altering the rows and cols variables:

Without any animation, this snippet is a bit boring – again, using TweenLite or some other tweening engine is the way to go.

Read snippet: Cut Image Into Squares

BitmapData & Particles

stage.frameRate = 30;
stage.quality = StageQuality.LOW;

var canvas:BitmapData = new BitmapData(400,400,false, 0x000000);
addChild(new Bitmap(canvas));
var overlay:BitmapData = new BitmapData(400,400,true, 0x12000000);
var particles:Dictionary = new Dictionary(true);

var blur:Array = [new BlurFilter(8,8,1)];
	
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	for (var i:int= 0; i<3; i++) createParticle();
	canvas.copyPixels(overlay, canvas.rect, new Point(0,0), null, null, true);
}
 
function createParticle():void{
	var s:MovieClip = new MovieClip();
	var diameter:Number = Math.random()*50 + 2;
	var radius:Number = diameter / 2;
	var mat:Matrix = new Matrix();
    mat.createGradientBox(diameter, diameter, 0, -radius, -radius);
	mat.createGradientBox(diameter, diameter, 0, -radius, -radius);
    s.graphics.beginGradientFill(GradientType.RADIAL, [ 0xFFCC32, 0xFF0000], [0.5,0.8], [0, 255], mat, SpreadMethod.PAD);
	s.graphics.drawCircle(0,0,radius);
	s.velX = 0;
	s.velY =  -Math.random()*6 + 3;
	s.posX = s.x = 150+ Math.random() * 100;
	s.posY = s.y = 200;
	s.theta= Math.random() * Math.PI * 2;
	s.inc = Math.random() * 0.4 + 0.01;
	s.rad = Math.random() * 4 + 1;
	s.filters = blur;
	// since the particles aren't on the display list, we need to keep a reference to them
	particles[s] = 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.velX = s.rad * Math.cos(s.theta);
	s.theta += s.inc;
	s.scaleX = s.scaleY -=  .03;
	if (s.scaleX < 0){
		particles[s] = null;
		s.removeEventListener(Event.ENTER_FRAME, onRunParticle);
	}
	s.x = s.posX;
	s.y = s.posY;
	canvas.draw(s, s.transform.matrix, null, BlendMode.ADD);
}

This is a slight variation on a simple particle system that I show in my intermediate class. It is almost the same as this example. But it makes use of filters and BitmapData.

Here is a still generated with this snippet. You’ll notice it vaguely resembles fire.

If you need more particles, there are other approaches that are more appropriate.

Read snippet: BitmapData & Particles

drawTriangles() 2D Textured Plane

[SWF(width = 700, height = 700)]

var loader:Loader = new Loader();
loader.load(new URLRequest("https://actionsnippet.com/wp-content/chair.jpg"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
var tex:BitmapData;
function onLoaded(evt:Event):void{
	tex = Bitmap(loader.content).bitmapData;
	addEventListener(Event.ENTER_FRAME, onLoop);
}

var plane:Shape = Shape(addChild(new Shape()));
plane.x = plane.y = 50;

var verts:Vector.<Number> = new Vector.<Number>();
var uvs:Vector.<Number> = new Vector.<Number>();
var indices:Vector.<int> = new Vector.<int>();
var rows:int = 30;
var size:Number = rows + 1;
var vertNum:Number = size * size;
var polySize:Number = 20;
var vIndex:int = 0;
var uvIndex:int = 0;
var gridSize:Number = rows * polySize;
for (var i:Number = 0; i<vertNum; i++){
	var xp:Number = i % size * polySize;
	var yp:Number =  int(i / size) * polySize;
	verts[vIndex++] = xp
	verts[vIndex++] = yp;
	uvs[uvIndex++] = xp / gridSize;
	uvs[uvIndex++] = yp / gridSize;
	if (i % size != rows){
		  indices.push(i, i+1, i+size, i+size, i+size+1, i+1);
	}
}

// render and show that the verts can be changed around
function onLoop(evt:Event):void {
	// shake the verts
	for (var i:int = 0; i<verts.length; i++){
		verts[i] += Math.random() - 0.5;
	}
	with(plane.graphics){
		clear();
		beginBitmapFill(tex,null, false, true);
		drawTriangles(verts, indices,uvs);
	}
}

This snippet is shows how to draw a textured 2D plane using drawTriangles(). This is similar to the wireframe 2D plane post from yesterday… the main difference is that you need to calculate UV coordinates if you want to use a bitmap fill with drawTriangles().

Here is a still of this snippet:

Read snippet: drawTriangles() 2D Textured Plane

Wireframe Plane 2D

var plane:Shape = Shape(addChild(new Shape()));
plane.x = plane.y = 50;

var verts:Vector.<Number> = new Vector.<Number>();
var indices:Vector.<int> = new Vector.<int>();
var rows:int = 20;
var size:Number = rows + 1;
var vertNum:Number = size * size;
var polySize:Number = 20;
var vIndex:int = 0;
for (var i:Number = 0; i<vertNum; i++){
	verts[vIndex++] = i % size * polySize;
	verts[vIndex++] = int(i / size) * polySize;
	if (i % size != rows){
		  indices.push(i, i+1, i+size, i+size, i+size+1, i+1);
	}
}

// render and show that the verts can be changed around
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	// shake the verts
	for (var i:int = 0; i<verts.length; i++){
		verts[i] += Math.random() - 0.5;
	}
	with(plane.graphics){
		clear();
		lineStyle(0,0);
		drawTriangles(verts, indices);
	}
}

This snippet shows a simple way to draw a 2D wireframe plane using drawTriangles(). To demonstrate the flexibility of the plane… the vertices are randomly shaken on enterframe.

Read snippet: Wireframe Plane 2D

drawTriangles() Terrain

[SWF(width=500,height=500,backgroundColor=0x333333, frameRate=40)]
var terrain:Shape = Shape(addChild(new Shape()));
terrain.x = terrain.y = 250;
var rows:int = 60;
var size:int = rows + 1;
var vertNum:int = size * size;
var polySize:Number = 5;
var gridWidth:Number = polySize * rows;
var halfWidth:Number = gridWidth / 2;
var verts:Vector.<Number> = new Vector.<Number>();
var pVerts:Vector.<Number> = new Vector.<Number>();
var indices:Vector.<int> = new Vector.<int>();
var uvs:Vector.<Number> = new Vector.<Number>();
var uvts:Vector.<Number> = new Vector.<Number>();
var tex:BitmapData = new BitmapData(gridWidth, gridWidth, false, 0x000000);
var pix:int = gridWidth * gridWidth;
var perlin:BitmapData = new BitmapData(gridWidth, gridWidth, false, 0x000000);
// generate the texture and the terrain
function generate():void{
	tex.fillRect(tex.rect, 0x000000);
	var i:Number, xp:Number, yp:Number;
	for (i = 0; i<pix; i++){
		xp = i % gridWidth;
		yp= int(i / gridWidth);
		var dx:Number = xp - gridWidth / 2;
		var dy:Number = yp - gridWidth / 2;
		var d:Number = 255 - Math.sqrt(dx * dx + dy * dy) / halfWidth* 255;
		if (d <0) d = 0;
		if (d> 255) d = 255;
		var c:uint = uint(d);
		tex.setPixel(xp, yp, c <<16 | c <<8 | c);
	}
	perlin.perlinNoise(100,100,3,Math.random()*100,false,false,7,true);
	perlin.draw(perlin, null, null, BlendMode.SCREEN);
	tex.draw(perlin, null, null, BlendMode.MULTIPLY);
	// calculate verts, uvs and indices
	var vIndex:int = 0;
	var uvIndex:int = 0;
	indices = new Vector.<int>();
	for (i = 0; i<vertNum; i++){
		var xMod:Number = i % size;
		xp = xMod * polySize;
		yp = int(i / size) * polySize;
		verts[vIndex++] = xp - halfWidth;
		verts[vIndex++] = yp - halfWidth;
		verts[vIndex++] = tex.getPixel(xp, yp) & 0xFF;
		uvs[uvIndex++] = xp /  gridWidth;
		uvs[uvIndex++] = yp / gridWidth;
		if (xMod != rows){
			  indices.push(i, i+1, i+size, i+1, i+size+1, i+size);
		}
	}
}
generate();
stage.addEventListener(MouseEvent.MOUSE_DOWN, onGenerate);
function onGenerate(evt:MouseEvent):void{ generate() };
var m:Matrix3D = new Matrix3D();
var rot:Number = 0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
		m.identity();
		var destRot:Number = mouseX / stage.stageWidth * 90;
		if (destRot <0) destRot = 0;
		if (destRot> 90) destRot = 90;
		rot += (destRot - rot) * 0.2;
		m.appendRotation(rot,Vector3D.Z_AXIS);
		m.appendRotation(60,Vector3D.X_AXIS);
		Utils3D.projectVectors(m, verts, pVerts, uvts);
		with(terrain.graphics){
			clear();
			beginBitmapFill(tex, null, false, true);
			drawTriangles(pVerts, indices, uvs, TriangleCulling.NEGATIVE);
		}
}

This snippet draws a pretty simple isometric terrain using fp10 graphics stuff and perlin noise.


Have a look at the swf here…

Read snippet: drawTriangles() Terrain

Variable Line Resolution #2

var loc:Vector.<Point> = new Vector.<Point>();
var lifts:Vector.<int> = new Vector.<int>();
var index:int = 0;
var resolution:int = 1;
var down:Boolean;
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyReleased);
addEventListener(Event.ENTER_FRAME, onLoop);
function onKeyReleased(evt:KeyboardEvent):void{
	if (evt.keyCode == Keyboard.RIGHT){
		resolution -= 1;
		if (resolution < 1) resolution = 1;
	}else 
	if (evt.keyCode == Keyboard.LEFT){
		resolution += 1;
	}
}
function onDown(evt:MouseEvent):void{
	down = true;
	lifts.push(index);
}
function onUp(evt:MouseEvent):void{
	down = false;
}
function onLoop(evt:Event):void {
	if (down){
		loc[index] = new Point(mouseX, mouseY);
		index++;
	}
	graphics.clear();
	graphics.lineStyle(0,0x000000);
	var j:int = 0;
	var lift:int;
	var liftLength:int = lifts.length;
	var lastLoc:int =  loc.length  - 1;
	for (var i:int = 0; i<liftLength; i++){
		j =  lifts[i];
		graphics.moveTo(loc[j].x, loc[j].y);
		if (i < liftLength - 1){
			lift = lifts[i + 1] - 1;
		}else{
			lift = lastLoc;
		}
		while (j < lift){
			j++;
			if (j % resolution == 1 || resolution == 1){
			  graphics.lineTo(loc[j].x, loc[j].y);
			}
		}
		graphics.lineTo(loc[j].x, loc[j].y);
	}
}

This snippet shows a simple approach to creating variable resolution graphics.

This is an improved version of yesterdays post. In yesterdays example the end points of the lines would sometimes be removed… this version doesn’t have that problem…

Below is a drawing created using this snippet. The left arrow key is used to decrease resolution and the right arrow key is used to increase resolution:

Have a look at the swf…

Read snippet: Variable Line Resolution #2

Variable Line Resolution

var loc:Vector.<Point> = new Vector.<Point>();
var lifts:Vector.<int> = new Vector.<int>();
var index:int = 0;
var resolution:int = 1;
var down:Boolean;
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
addEventListener(Event.ENTER_FRAME, onLoop);
function onKeyReleased(evt:KeyboardEvent):void{
	if (evt.keyCode == Keyboard.RIGHT){
		resolution -= 1;
		if (resolution < 1) resolution = 1;
	}else 
	if (evt.keyCode == Keyboard.LEFT){
		resolution += 1;
	}
}
function onDown(evt:MouseEvent):void{
	down = true;
	lifts.push(index);
}
function onUp(evt:MouseEvent):void{
	down = false;
}
function onLoop(evt:Event):void {
	if (down){
		loc[index] = new Point(mouseX, mouseY);
		index++;
	}
	graphics.clear();
	graphics.lineStyle(0,0x000000);
	var liftIndex:int = 0;
	for (var i:int = 0; i<loc.length; i++){
		if (liftIndex == lifts.length) liftIndex = 0;
		if (i == lifts[liftIndex]){
			graphics.moveTo(loc[i].x, loc[i].y);
		    liftIndex++;
		}else{
			if (i % resolution == 1 || resolution == 1){
				graphics.lineTo(loc[i].x, loc[i].y);
			}
		}
	}
}

This snippet shows a simple approach to creating variable resolution graphics.

Below is a drawing done using this snippet. The left arrow key is used to decrease resolution and the right arrow key is used to increase resolution:


Click to view swf…

Read snippet: Variable Line Resolution

Utils3D.projectVectors() Lathe

[SWF(width = 500, height = 500, backgroundColor = 0x000000)]
var halfWidth:Number = stage.stageWidth / 2;
var halfHeight:Number = stage.stageHeight / 2;
var loc:Vector.<Number>;

graphics.lineStyle(0, 0xFF0000);
graphics.moveTo(halfWidth, 0);
graphics.lineTo(halfWidth, stage.stageHeight);
graphics.moveTo(0, halfHeight);
graphics.lineTo(stage.stageWidth, halfHeight);

var line:Shape = Shape(addChild(new Shape()));
line.x = halfWidth;

var idle:Function = function(){};
var currentMode:Function = idle;
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
addEventListener(Event.ENTER_FRAME, onLoop);
function onDown(evt:MouseEvent):void{
	if (contains(frame)){
		removeChild(frame);
		currentMode = idle;
		line.graphics.clear();
		return;
	}
	loc = new Vector.<Number>();
	line.graphics.lineStyle(0,0xFFFFFF);
	line.x = halfWidth
	line.y = halfHeight;
	line.graphics.moveTo(line.mouseX, line.mouseY);
	currentMode = captureLocs;
	canvas.fillRect(canvas.rect, 0x000000);
}
function onUp(evt:MouseEvent):void{
	if (currentMode == idle) return;
	setupLathe();
	currentMode = showLathe;
}

function onLoop(evt:Event):void{
	currentMode();
}
function captureLocs():void{
	loc.push(line.mouseX);
	loc.push(line.mouseY);
	loc.push(0);
	line.graphics.lineTo(line.mouseX, line.mouseY);
}
/**
 -- Lathe Stuff:
*/
var canvas:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight,false, 0x000000);
var frame:Bitmap = new Bitmap(canvas);
var dx:Number=0;
var dy:Number=0;
 var matrix:Matrix3D = new Matrix3D();
var pVerts:Vector.<Number>;
var uvts:Vector.<Number>;
function setupLathe():void{
	addChild(frame);
	pVerts =  new Vector.<Number>();
	uvts = new Vector.<Number>();
	var nVerts:Vector.<Number> = new Vector.<Number>();
	var tVerts:Vector.<Number> = new Vector.<Number>();
	matrix.identity();
	var step:Number = 2;
	for (var i:int = 0; i <360; i+=step){
		matrix.appendRotation(step,Vector3D.Y_AXIS);
		matrix.transformVectors(loc, tVerts);
		nVerts = nVerts.concat(tVerts);
	}
	loc = nVerts.concat();
}
function showLathe():void{
	dx += (mouseX - dx)/4;
	dy += (mouseY - dy)/4;
	matrix.identity();
	matrix.appendRotation(dy,Vector3D.X_AXIS);
	matrix.appendRotation(dx,Vector3D.Y_AXIS);
	matrix.appendTranslation(halfWidth, halfHeight, 0);
	Utils3D.projectVectors(matrix, loc, pVerts, uvts);
	canvas.lock();
	canvas.fillRect(canvas.rect, 0x000000);
	var leng:int = pVerts.length;
	for (var i:int = 0; i<leng; i+=2){
		canvas.setPixel( pVerts[i], pVerts[i + 1], 0xFFFFFF);
	}
	canvas.unlock();
}

This snippet allows you to create 3D lathe shapes by drawing a 2D line. This is done using Utils3D.projectVectors() and Matrix.transformVectors().

Have a look at the swf here…

Read snippet: Utils3D.projectVectors() Lathe

FileReference.load()

var txt:TextField = TextField(addChild(new TextField()));
txt.autoSize = TextFieldAutoSize.LEFT;
txt.x = txt.y = 20;
txt.text = "click anywhere to load an image file...";

var fileRef:FileReference= new FileReference();
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
function onDown(evt:MouseEvent):void{
    fileRef.browse([new FileFilter("Images", "*.jpg;*.gif;*.png")]);
	fileRef.addEventListener(Event.SELECT, onSelected);
	stage.removeEventListener(MouseEvent.MOUSE_DOWN, onDown);
}
function onSelected(evt:Event):void{
	fileRef.addEventListener(Event.COMPLETE, onLoaded);
	fileRef.load();
	fileRef.removeEventListener(Event.SELECT, onSelected);
}
function onLoaded(evt:Event):void{
	var loader:Loader = new Loader();
	loader.loadBytes(evt.target.data);
	addChild(loader);
	fileRef.removeEventListener(Event.COMPLETE, onLoaded);
}

This snippet shows how to use the FileReference.load() method to load an image into flash player RAM and display it on the stage.

Read snippet: FileReference.load()

Counter Function

var counter:Function = function(count:Array):Function{
	var leng:int = count.length;
	var index:int = 0;
	return counter = function(reset:*=""):Function{
		if (reset=="reset"){
			index = 0;
			return counter;
		}else
		if (reset is Array){
			count = reset;
			return counter;
		}
		trace(count[index % leng]);
		index++;
		return counter;
	}
}

// first time it's called you pass an array
trace("count through the array:");
// you can optionally call trigger the counter by calling the newly
// returned function
counter(["a","b","c"])();
counter();
counter();
trace("change the array:");
// here we choose to simply set the array and not trigger the counter
counter([10,20,40,60,80]);
counter();
counter()
trace("reset the counter:");
// reset and the counter is called 3 times
counter("reset")()()();

/*outputs :
count through the array:
a
b
c
change the array:
10
20
reset the counter:
10
20
40
*/

Today I felt like messing around with functions and this is the result. This snippet shows a strange and interesting technique to create a function that iterates through a given array in a few different ways.

I believe the technical term for this kind of thing is a continuation…

There are a bunch of other posts like this on actionsnippet. Some are purely experimental, others are actually quite useful… these can all be found in the functions category.

Read snippet: Counter Function