AS3 Quick Tip – Remove a specific item from an array.

I’ve been working on a project today and needed a function to remove a specific item from an array. This is what I came up with, so I thought I’d share it here.

var myArrayOfLetters:Array = ["a","b","c","c","d","e","f","g","c"];
removeItemArray(myArrayOfLetters,"c");
//This will remove all instances of "c" from your array - so you will end up with
//a,b,d,e,f,g
 
function removeItemArray(thearray, theItem):void{
	trace("Remove "+theItem+" from "+thearray);
	for(var i:int=0; i

This will remove all instances of theItem from your array. If you know there will only be one instance of the item in the array, you can add "break;" to the conditional in the loop to save CPU.

var myArrayOfLetters:Array = ["a","b","c","d","e","f","g"];
removeItemArray(myArrayOfLetters,"c");
//This will remove the first instance of "c" from your array - so you will end up with
//a,b,d,e,f,g

function removeItemArray(thearray , theItem):void{
	trace("Remove "+theItem+" from "+thearray );
	for(var i:int=0; i

Hope you find it useful.
Lawrie.

Open Processing

Following on from my post about Daniel Shiffman’s Nature of Code, and the benefits of digging into the processing community, here’s a post about the excellent site OpenProcessing.org

“What? A website to share Processing sketches??”
Share your sketches with others.
Help and collaborate with the community.
Improve and polish your programming skills.

Even if you’re not delving into Processing development yet, there are some amazing examples on the site, which should provide you with some inspiration and ideas, no matter what platform you use. Just check out some of thse incredible pieces –

Empathy –

pEmpathy

Awesome! And here’s the code that makes it –

/** 

Don't move too fast — you might scare it. Click to forgive and forget.

*/ int n = 5000; // number of cells float bd = 37; // base line length float sp = 0.004; // rotation speed step float sl = .97; // slow down rate Cell[] all = new Cell[n]; class Cell{ int x, y; float s = 0; // spin velocity float c = 0; // current angle Cell(int x, int y) { this.x=x; this.y=y; } void sense() { if(pmouseX != 0 || pmouseY != 0) s += sp * det(x, y, pmouseX, pmouseY, mouseX, mouseY) / (dist(x, y, mouseX, mouseY) + 1); s *= sl; c += s; float d = bd * s + .001; line(x, y, x + d * cos(c), y + d * sin(c)); } } void setup(){ size(300, 300, P2D); stroke(0, 0, 0, 20); for(int i = 0; i < n; i++){ float a = i + random(0, PI / 9); float r = ((i / (float) n) * (width / 2) * (((n-i) / (float) n) * 3.3)) + random(-3,3) + 3; all[i] = new Cell(int(r*cos(a)) + (width/2), int(r*sin(a)) + (height/2)); } } void draw() { background(255); for(int i = 0; i < n; i++) all[i].sense(); } void mousePressed() { for(int i=0;i

And that's just one of hundreds of amazing Processing sketches. Here's some more of my favourites.

Scrunch / Flower generator -

pFLower

Spring Snipper -

pSpring

Scattered Letters -

pLetters

Nebula -

pNebula

Spiral Galaxy Mutation -

pGalaxy

Shiffman Vector movement – from Processing to Flash

I’ve been playing about with processing lately, which is really good fun, and quite easy to jump straight into, coming from a Flash background. If you’ve not heard of Processing, it’s –

Processing is an open source project initiated by Casey Reas and Benjamin Fry, both formerly of the Aesthetics and Computation Group at the MIT Media Lab. It is “a programming language and integrated development environment (IDE) built for the electronic arts and visual design communities”, which aims to teach the basics of computer programming in a visual context, and to serve as the foundation for electronic sketchbooks. One of the stated aims of Processing is to act as a tool to get non-programmers started with programming, through the instant gratification of visual feedback. The language builds on the graphical capabilities of the Java programming language, simplifying features and creating a few new ones.

It’s free too! You can grab a copy here.

One of the authorities on Processing is Daniel Shiffman, author of Learning Processing. There’s loads of great content on his site, for the budding developer. One of the most interesting is his section The Nature Of Code. It’s actually the sylabus for a course he teaches, but it makes for great online reading, explaining not only the how, but also the why behind all the programming concepts.

I spent a while digging through the chapter on Vectors (for motion, not graphics), played around with the code in Processing, then ported some of it to Flash.

This is just a quick experiment really, and the code below if not the best way of doing things, but I thought it was an interesting effect none-the-less. Using various vectors in flash, I’ve made a weird springy thing. Move your mouse to swirl it around – press space to restart it – and toggle the limit bounds feature.

[kml_flashembed publishmethod=”static” fversion=”9.0.0″ movie=”flash-content/shiffman/shiffmanVectorsAS3.swf” width=”300″ height=”300″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

And here’s the code – uncommented, unoptimised, but you get the idea :)

stage.quality = StageQuality.LOW;
stage.frameRate = 120;
var makeBalls:int = 200;
var movers:Array= [];
var divVar:int = 500;
var mouse = {x:mouseX,y:mouseY}
var springDivider:Number = 25;
var constrainBounds:Boolean = false;
var SW:Number= stage.stageWidth;
var SH:Number= stage.stageHeight;

construct();

function construct():void{
	for (var i:int = 0; i < makeBalls; i++) {
		movers[i] = makeMover(i);
		movers[i].addEventListener(Event.ENTER_FRAME, update);
		addChild(movers[i]);
	}
}

function makeMover(i):DisplayObject{
	
var m:MovieClip = new MovieClip();//new M();

	m.graphics.beginFill( 0xFFCC0000, .5);
	m.graphics.drawCircle(0,0,5);
			
	m.location 		=  {x:SW/2,y:SH/2};
	m.velocity 		=  {x:0,y:0};
	m.acceleration  =  {x:0,y:0};
	m.topspeed 		=  (i/springDivider)+1;
	
	return m;
}


function update(e:Event):void {
	
	var M   = e.currentTarget;
	var dir = {x:mouseX-M.x,y:mouseY-M.y};
	
	M.acceleration.x = dir.x/divVar;
	M.acceleration.y = dir.y/divVar;
	
	M.velocity.x+=M.acceleration.x;
	M.velocity.y+=M.acceleration.y;
	
	if(M.velocity.x>M.topspeed){M.velocity.x=M.topspeed}
	if(M.velocity.y>M.topspeed){M.velocity.y=M.topspeed}
	
	if(M.velocity.x< -M.topspeed){M.velocity.x=-M.topspeed}
	if(M.velocity.y<-M.topspeed){M.velocity.y=-M.topspeed}
	
	M.location.x+=M.velocity.x;
	M.location.y+=M.velocity.y;	
	
	M.x = M.location.x;
	M.y = M.location.y;
	
	if(constrainBounds){
		if (M.location.x > SW) {
			M.location.x = 0;
		} else if (M.location.x < 0) {
			M.location.x = SW;
		}
		if (M.location.y > SH) {
			M.location.y = 0;
		} else if (M.location.y < 0) {
			M.location.y = SH;
		}
	}
}

stage.addEventListener(Event.ENTER_FRAME, updateMouse);
function updateMouse(e:Event):void{
	mouse.x = mouseX;
	mouse.y = mouseY;
}

stage.addEventListener( KeyboardEvent.KEY_UP, keyUpHandler );
function keyUpHandler( e:KeyboardEvent ):void {
	if (e.keyCode==32) {
		
		if(constrainBounds){constrainBounds=false}
		else{constrainBounds=true}
		
		reset();
	}
}

function reset():void{
	for (var i:int = 0; i < makeBalls; i++) {
		movers[i].removeEventListener(Event.ENTER_FRAME, update);
		movers[i].parent.removeChild(movers[i]);
	}
	movers = [];
	construct();
}

Well that’s just Wonderfl

wondefl

I’ve been using Wonderfl.net more and more over the last few weeks. It’s an amazing site, with a great community – I I’m looking forwards to playing with it, when I’ve got a couple of hours to kill on an internet café computer somewhere on the road.

For those of you not familiar with it yet, here’s a description from the site –

Usually when you want to build Flash, you need Flash IDE or Flex, FlashDevelop or any flash building tool to write code and compile it.

With wonderfl, you write Actionscript3 code in the html form, and our server compiles your code.
You’ll see warnings, maybe errors from the compiler, and if your code is valid, your Flash (swf) will be automatically shown besides your code.

Write code and watch it in action, realtime, in your browser.

It’s a really amazing service, and it’s totally free. The community around it is really strong too, because at the click of a button, you can “fork” any of the posts on the site, edit a line or two, and see how it changes things. Add ot that the heavy hitters of the flash world posting regular examples, and the best and brightest Japanese Flashers posting amazing examples, and you’ve got a pretty incredible site.

Another thing I like about it, is that it compiles in Flash Player 10, so those of you stuck using CS3 or earlier, can get your hands dirty with the native 3D methods, and other new FP10 goodies.

You can check out my profile here, and edit some of my code with the click of a button. Here’s a few still from some of my posts –

wonder1

wonder2

wonder23jpg

Cheers.
Lawrie.

50 red Retrospective – and AS3 source code

A few months ago, I looked back at my best performing flash games – the aptly named “Super Letter Game“, and showed how a similar control scheme can be coded in AS3.

Today I’m going to look back over another of my AS2 games, which was reasonablly successful – 50 Red.


50Red

Interactive artwork meets frantic clicking game in this all new sensory overloading game – 50 Red! Click 50 red balls as fast as possible whilst avoiding the blue balls for a place on the high scores table. WARNING – FLASHING IMAGES!

You can play 50 Red here.

50 Red was a fun project to work on, but maybe not the ideal basis for a game. It was based heavily on a university project I completed for a generative arts class – and so I think the “game” element feels a little tacked on. None-the-less, 50 Red has gone on to have around half a million plays, and used some interesting flash techniques.

I’ve rewritten the basic functions of 50 red in AS3, which you can see in the demo below. There a couple of key variables in there which are randomised when the game loads – so it should appear differently each time you load it.

Here’s the SWF we’re going to be producing –

[kml_flashembed publishmethod=”static” fversion=”9.0.0″ movie=”flash-content/50redas3/50RedBlog.swf” width=”450″ height=”450″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

And here’s the code that produces it –

/// - Variables - ///
var randomRotationSetting:int = Math.round(Math.random()*100);
var scaleDivider:int 		  = Math.round(Math.random()*10000);
var scoreVar:int 			  = 0;
/// - Constructor - ///
//Make 250 balls -
for (var i:int =0; i<250; i++) {
	var h:MovieClip = new MovieClip();
	//if we're on an even number -
	if (i%2) {
		//Make it red
		h.graphics.beginFill( 0xFFFF0000, 1);
		//And add a listener to call the clickRed function when it is clicked.
		h.addEventListener(MouseEvent.MOUSE_DOWN, clickRed);
	} else {
		//Otherwise make it blue
		h.graphics.beginFill( 0xFF0000FF, 1);
		//And add the clickBlue function instead.
		h.addEventListener(MouseEvent.MOUSE_DOWN, clickBlue);
	}
	//Setting the button mode to true makes flash use the hand icon
	h.buttonMode = true;
	//Draw a circle, at position x:0,y:-50,with a radius of 10.
	h.graphics.drawCircle(0,-50,10);
	//And center it on stage
	h.x = stage.stageWidth/2;
	h.y = stage.stageHeight/2;
	//And set it's number to i - the step through the for loop.
	h.myNum= i;
	//Set the ball's rotation -
	h.rotation = i*randomRotationSetting;
	//Set the ball's scale -
	h.scaleY = h.scaleX= (i*i)/scaleDivider;//i/100;
	//Add an event listener to update the ball's position every frame -
	h.addEventListener(Event.ENTER_FRAME, updatePosition);
	addChild(h);
}
/// - Updater - ///
function updatePosition(e:Event):void {
	//Rotate the current ball by an amount calculated from it's number -
	e.currentTarget.rotation+=(Math.PI*(e.currentTarget.myNum/2))/50;
}
/// - Click Handlers - ///
//These are called when the balls are clicked -
function clickRed(e:Event):void {
	//Make a reference to the current ball
	var ball = e.currentTarget;
	//Remove the listeners from the ball before we destroy it -
	ball.removeEventListener(Event.ENTER_FRAME, updatePosition);
	ball.removeEventListener(MouseEvent.MOUSE_DOWN, clickRed);
	//Remove the ball from the display list.
	ball.parent.removeChild(ball);
	trace("Win a point!");
	//Add a point to the score variable
	scoreVar+=1;
	//Call the update score function
	updateScore();
}
function clickBlue(e:Event):void {
	//As with the above function - except we are removing the clickBlue listener
	//and subtracting a point
	var ball = e.currentTarget;
	ball.removeEventListener(Event.ENTER_FRAME, updatePosition);
	ball.removeEventListener(MouseEvent.MOUSE_DOWN, clickBlue);
	ball.parent.removeChild(ball);
	trace("Lose a point!");
	scoreVar-=1;
	updateScore();
}
/// - Scores text box - ///
//Create a new text field on the stage
var tf:TextField = new TextField();
tf.width = stage.stageWidth
addChild(tf);
//Set the initial text -
tf.text = "Clicking a red ball adds one point, clicking a blue ball loses one. Can you get 10 points?";
//This is called to update the scores text
function updateScore():void {
	//If your score is higher than 10 - you win the game!
	if (scoreVar>10) {
		tf.text = "You have won the game!";
	}
	else{
		tf.text = "Score - "+scoreVar;
	}
}
//That's it!

This week, I’ve also been digging deeper into the very cool Wonderfl, an online Flash compiler. Now you can code AS3 flash files straight from your web browser! I’ll hopefully be doing a full post about it soon, but for thew time being, why not have a look at this tutorial code on wonderfl. I’ve added in some nice alpha transparency, changing colours and even some 3D rotation thanks to Flah Player 10.


50RedWonderfl

Let me know if you use this code for anything, as I’d love to see it.
Have fun.
Lawrie.