14 December 2010

Snowfall Flash Animation Effect Example

This simple example is based on two previous posts:

1) Simple Flash Snowflake Generator and
2) Flash Tutorial : Rain Effect

Instead of using AS2 as in Rain Effect Tutorial, this is pure AS3 code.



hosted on ShareSWF

You can expect more complex examples later. Ask if you need further explanation.

*_*

12 December 2010

Simple Flash Snowflake Generator

Just like every year, few weeks before holidays there is plethora of animations which includes Santa, snow, various gift boxes, evergreen trees etc. Many of them are quite good as Christmas and New Year Flash cards, but almost all of them has one small shortage - snowflakes are made from same single MovieClip. Now if objects are small and distant that's fine, but to imitate depth some animations display bigger graphics and defect is visible.

They say in real life there isn't two exact the same snowflakes, so I decided to solve this problem and create simple Snowflake Generator which will randomly create slightly different snowflake every time object is created.

I don't have to generate entire snowflake at once, because snowflake is symmetric object in two ways.



Take a look at a blue shape above. Points A, B and C are randomly generated, but they must be placed inside appropriate rectangles. After the shape is drawn, we copy the same shape and place it in mirrored position. Combined object is then copied 5 times and rotated for 60 degrees per object. In this way we will get 6 movie clips which forms single randomly created snowflake! Every time we call new snowflake() we get just a little bit of different shape. Nice.

ActionScript 3.0 doesn't have duplicateMovieClip() method (this has been discussed widely on forums and some workarounds have been made) and in this case I will just create 6 different MovieClips and draw same graphic shape inside them. Six clips act as single snowflake which can be further animated to simulate falling snow Flash animation.

We create new MovieClip and inside we place next code:

x = stage.stageWidth/2;
y = stage.stageHeight/2;

var field1:MovieClip = new MovieClip();
var field2:MovieClip = new MovieClip();
var field3:MovieClip = new MovieClip();
var field4:MovieClip = new MovieClip();
var field5:MovieClip = new MovieClip();
var field6:MovieClip = new MovieClip();

function drawFlake(mc:MovieClip):void
{
mc.graphics.beginFill(0xffffff);
mc.graphics.lineTo(0, 80);
mc.graphics.lineTo(aX, aY);
mc.graphics.lineTo(bX, bY);
mc.graphics.lineTo(cX, cY);
mc.graphics.lineTo(0, 0);
mc.graphics.lineTo(0, 80);
mc.graphics.lineTo(-aX, aY);
mc.graphics.lineTo(-bX, bY);
mc.graphics.lineTo(-cX, cY);
mc.graphics.lineTo(0, 0);
mc.graphics.endFill();
}

var aX = Math.random()*10+10; // (10-20)
var aY = Math.random()*20+60; // (60-80)
var bX = Math.random()*10; // (0-10)
var bY = Math.random()*20+40; // (40-60)
var cX = Math.random()*10+10; // (10-20)
var cY = Math.random()*20+20; // (20-40)

drawFlake(field1);
addChild(field1);

drawFlake(field2);
field2.rotation = 60;
addChild(field2);

drawFlake(field3);
field3.rotation = 120;
addChild(field3);

drawFlake(field4);
field4.rotation = 180;
addChild(field4);

drawFlake(field5);
field5.rotation = 240;
addChild(field5);

drawFlake(field6);
field6.rotation = 300;
addChild(field6);

DrawFlake function actually draws two symmetric shapes based on three Points with randomly chosen position. On main timeline we only have to call our snowflake like it:

var flake:snowflake = new snowflake();
addChild(flake);



*_*

29 October 2010

Free Flash + AS3 + Flex Tutorials e-book

About two months ago I published my first e-book on Lulu. At first, idea was to create collection of better tutorials from this blog, which I'm writing for the past 3 and a half years. Initially, there was a small price under 5 bucks, but two months later I sold only 1 copy, so I decided to give it away for free. Actually, I wasn't selling the book, it was more like a small-donation-model to keep my blog running.

Right now, you can download the book from LULU pages or from Scribd.

As previously planned I'll update my e-book every 3-4 months with new tutorials and maybe few not available on this blog :)

*_*

19 October 2010

Custom Flex 4 HornLayout variation

Few days ago I presented custom Flex 4 TriangleLayout. Another variation of this layout would be when individual items are ordered from left to right, unlike in TrinagleLayout where items are placed top to bottom.



Code is almost the same, just a minor differences.

HornLayout.as


package com.flash2nd.layout {

// author: http://flanture.blogspot.com - www.flash2nd.com
// license: http://creativecommons.org/licenses/by/3.0/
// October 2010

import mx.core.ILayoutElement;
import mx.utils.ObjectUtil;

import spark.layouts.supportClasses.LayoutBase;

public class HornLayout extends LayoutBase {

public function HornLayout() {
super();
}

override public function measure():void {
super.measure();
}

override public function updateDisplayList(width:Number, height:Number):void {
super.updateDisplayList(width,height);

if(target){
var count:int = target.numElements;
var layoutElement:ILayoutElement;
var startX:Number = 0;
var startY:Number = target.height/2;
var shift:int = 1;

for(var i:int = 1; i < count+1; i++){
// find current level
var level:int = findLevel(i);

layoutElement = target.getElementAt(i-1);
layoutElement.setLayoutBoundsSize(NaN,NaN);

var elWidth:Number = layoutElement.getLayoutBoundsWidth();
var elHeight:Number = layoutElement.getLayoutBoundsHeight();

if (level !== findLevel(i-1)) {
shift = i;
}

var x:Number = startX + elWidth * (level - 1) * 2;
var y:Number = startY - elHeight * (level - 1) + (i % shift) * elHeight * 2;

layoutElement.setLayoutBoundsPosition(x,y);
}
}

}

private function findLevel(index:int):int {
var levelCounter:int = 1;
var sum:int = 1;
while (sum < index) {
sum += levelCounter;
if (sum <= index) {
levelCounter += 1;
}
}
return levelCounter;
}

}
}



HornLayoutTest.mxml


<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:layout="com.flash2nd.layout.*"
width="100%" height="100%">


<s:layout>
<layout:HornLayout/>
</s:layout>

<s:Button label="Button A"/>
<s:Button label="Button B"/>
<s:Button label="Button C"/>
<s:Button label="Button D"/>
<s:Button label="Button E"/>
<s:Button label="Button F"/>
<s:Button label="Button G"/>
<s:Button label="Button H"/>
<s:Button label="Button I"/>
<s:Button label="Button J"/>
<s:Button label="Button K"/>
<s:Button label="Button L"/>
<s:Button label="Button M"/>
<s:Button label="Button N"/>
<s:Button label="Button O"/>
<s:Button label="Button P"/>
<s:Button label="Button Q"/>
<s:Button label="Button R"/>

</s:Application>


sharing is caring :)
thanx.

*_*

16 October 2010

Discrete versus continual graphical AS3 Timer

Some Flash games require level timers. If mission is not complete when timer runs out, hero is dead. Usually you have two types of timers, numerical level timer and graphical timer.

On the other hand, graphical timer can be discrete or continual. Actually all graphical timers are discrete, when you think about it, just updates happen more frequently and user sees it like continual.

Here is how to create both discrete and continual graphic timers.

step 1.

First we set up some background color.


// background elements

var b1:Sprite = new Sprite();
b1.graphics.beginFill(0x33cc33);
b1.graphics.drawRect(0,0,stage.stageWidth,20);
addChild(b1);

var b2:Sprite = new Sprite();
b2.graphics.beginFill(0x33cc33);
b2.graphics.drawRect(0,25,stage.stageWidth,20);
addChild(b2);


step 2.

We write our discrete timer. Here is complete function.


function gTimer(seconds:int):void
{
var t:Timer = new Timer(1000, seconds);

var w:Number = stage.stageWidth;
var h:Number = 20;
var g:Sprite = new Sprite();
addChild(g);

t.addEventListener(TimerEvent.TIMER, onTimer);
function onTimer(evt:Event):void
{
var cc:int = evt.target.currentCount;
var gWidth:Number = (cc * w)/seconds;
g.graphics.beginFill(0x339933);
g.graphics.drawRect(0, 0, gWidth, h);
}
t.start();
}


Why this timer is 'discrete'? Because graphic update happens once every 1000 milliseconds. We see graphic change in distinct time intervals of one second.

Code is simple, only thing worth explanation is gWidth variable which is just proportion used to calculate current timer width.

step 3.

We write our continual timer. Here is complete function.


function cgTimer(seconds:int):void
{
var t:Timer = new Timer(50, seconds*20);

var w:Number = stage.stageWidth;
var h:Number = 20;
var g:Sprite = new Sprite();
addChild(g);

t.addEventListener(TimerEvent.TIMER, onTimer);
function onTimer(evt:Event):void
{
var cc:int = evt.target.currentCount;
var gWidth:Number = (cc * w)/(seconds * 20);
g.graphics.beginFill(0x339933);
g.graphics.drawRect(0, 25, gWidth, h);
}
t.start();
}


Code is exactly the same as in discrete graphical timer, with one minor change. Timer is called every 50 milliseconds and because those time intervals are so small, user sees this timer as continual one.

step 4.

We test our timers.

gTimer(24);
cgTimer(24);

Now, take your stopwatch and you will see that even both timers start in approximately the same time, discrete timer will finish first and both timers will finish after more than 24 seconds, discrete one in about 25,5 seconds and continual one almost 2 seconds later (at least on my computer).

This is not some error. Continual timer makes a lot more calculations than discrete one, hence difference. Just something you should be aware of when making games.

*_*

11 October 2010

Custom Flex 4 Spark TriangleLayout

Since Spark has separated layouts from components, now we have greater control of how final application will look like. Basic Flex 4 layouts are BasicLayout, HorizontalLayout, VerticalLayout and TileLayout.

However, one even more important feature is that you can create your own custom layouts by extendending LayoutBase class inside spark.layouts library or any of its subclasses.



TriangleLayout takes any given number of display elements and form triangle out of them, where first element is on top level, second and third on second level below, etc.

TriangleTest.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:layout="com.flash2nd.layout.*"
width="100%" height="100%">


<s:layout>
<layout:TriangleLayout/>
</s:layout>

<s:Button label="Button 1"/>
<s:Button label="Button 2"/>
<s:Button label="Button 3"/>
<s:Button label="Button 4"/>
<s:Button label="Button 5"/>
<s:Button label="Button 6"/>
<s:Button label="Button 7"/>
<s:Button label="Button 8"/>
<s:Button label="Button 9"/>
<s:Button label="Button 10"/>
<s:Button label="Button 11"/>
<s:Button label="Button 12"/>
<s:Button label="Button 13"/>
<s:Button label="Button 14"/>

</s:Application>


As mentioned before, TriangleLayout class extends LayoutBase class and overrides two methods: measure() and updateDisplayList(w,h).

I'm not going into details how code works, but if you need deeper understanding of it, feel free to email me with your questions.

TriangleLayout.as

package com.flash2nd.layout {

// author: http://flanture.blogspot.com - www.flash2nd.com
// license: http://creativecommons.org/licenses/by/3.0/
// October 2010

import mx.core.ILayoutElement;
import mx.utils.ObjectUtil;

import spark.layouts.supportClasses.LayoutBase;

public class TriangleLayout extends LayoutBase {

public function TriangleLayout() {
super();
}

override public function measure():void {
super.measure();
}

override public function updateDisplayList(width:Number, height:Number):void {
super.updateDisplayList(width,height);

if(target){
var count:int = target.numElements;
var layoutElement:ILayoutElement;
var startX:Number = target.width/2;
var startY:Number = 0;
var shift:int = 1;

for(var i:int = 1; i < count+1; i++){
// find current level
var level:int = findLevel(i);

layoutElement = target.getElementAt(i-1);
layoutElement.setLayoutBoundsSize(NaN,NaN);

var elWidth:Number = layoutElement.getLayoutBoundsWidth();
var elHeight:Number = layoutElement.getLayoutBoundsHeight();

if (level !== findLevel(i-1)) {
shift = i;
}
var x:Number = startX - elWidth * (level - 1) + (i % shift) * elWidth * 2;
var y:Number = startY + elHeight * level * 2;

layoutElement.setLayoutBoundsPosition(x,y);
}
}

}

private function findLevel(index:int):int {
var levelCounter:int = 1;
var sum:int = 1;
while (sum < index) {
sum += levelCounter;
if (sum <= index) {
levelCounter += 1;
}
}
return levelCounter;
}

}
}



You can also download TriangleLayout source code.

*_*

27 September 2010

Flex Enterprise Development

In building Rich Internet Applications for enterprise you will need much more than online tutorials and documentation. There isn't many books about the subject, because entire field is still young but very promising. Industry needs are high right now and there's huge void where good developers should exist.

In order to bridge this gap, experienced Adobe Certified Flex Instructors Yakov Fain and Victor Rasputnis together with another Farata Systems developer Anatole Tartakovsky have published "Enterprise Development with Flex", one of the first (if not THE first) book to guide new developers into this cutting-edge field with best practices and techniques tips.

This 680+ pages book is must-have item for one more reason, it is included in Adobe Developer Library and recommended by Adobe Flex team members.

*_*

19 September 2010

Align Buttons in Flex Spark layout container

Let's say Buttons inside same group in your Flex app have different text (which is almost always the case). Code may look something like this:

<?xml version="1.0" encoding="utf-8"?>
<s:Application

xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">

<s:Group top="10" left="10">
<s:layout>
<s:VerticalLayout />
</s:layout>
<s:Button label="first button" />
<s:Button label="second button" />
<s:Button label="third button" />
<s:Button label="forth button" />
</s:Group>
</s:Application>


Now, your Buttons have different sizes and you want all of them to have same size. You can set sizes of all Button to size of Button with highest width value using horizontalAlign="justify" property/value.

align buttons in flex spark

<?xml version="1.0" encoding="utf-8"?>
<s:Application

xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">

<s:Group top="10" left="10">
<s:layout>
<s:VerticalLayout horizontalAlign="justify" />
</s:layout>

<s:Button label="first button" />
<s:Button label="second button" />
<s:Button label="third button" />
<s:Button label="forth button" />
</s:Group>
</s:Application>

17 September 2010

One memory cell AS3 bot

It's all about instructions, not memory. Even one memory cell bot can have interesting life if instructions are written properly. To demonstrate this we'll start with most simple bot out there - the crazy bot.

The crazy bot doesn't have any memory. Every frame (or any other given time interval) crazy bot randomly choses its next destination. Create new Movie Clip with linkage name 'bot' and type next code on Timeline first frame (stage size is standard 550x400):

var _bot:bot = new bot();
addChild(_bot);
_bot.x = 275;
_bot.y = 200;

var dx;
var dy;

addEventListener(Event.ENTER_FRAME, onframe);
function onframe(evt:Event):void
{
mover(_bot);
}

function mover(a:bot):void
{
dx = Math.random()*10-5;
dy = Math.random()*10-5;

a.x += dx;
a.y += dy;
}


Now, this is one crazy bot! First 4 lines we put our bot in center of the Stage. Next we define dx and dy variables to store frame-by-frame movement. We define event listener to move our bot every frame. We do this in mover function, where every frame we get randomly chosen values between -5 and 5. This is how much our bot will move in pixels in two directions, on x and on y axis.

Now, I'll add only one memory cell to our bot. This cell will store first randomly chosen value for x axis direction. Let's see entire code first:

var _bot:bot = new bot();
addChild(_bot);
_bot.x = 275;
_bot.y = 200;

var info:Object = new Object();
info.startX = _bot.x;
info.startY = _bot.y;
info.memory = new Array();
var dx;
var dy;

function mover(a:bot):void
{
if (info.memory.length > 0)
{
if (info.memory[0] > 0)
{
dy = Math.random()*20-10;
dx = Math.random()*10;
} else {
dy = Math.random()*20-10;
dx = Math.random()*(-10);
}
} else {
dy = Math.random()*10-5;
dx = Math.random()*10-5;
}

info.memory[0] = dx;
a.x += dx;
a.y += dy;
info.startX = a.x;
info.startY = a.y;

if( (a.x > 550)||(a.x < 0)||(a.y > 400)||(a.y < 0) )
{
a.x = 275;
a.y = 200;
info.memory[0] = -1 * info.memory[0];
}

// var _dot:dot = new dot();
// _dot.x = a.x;
// _dot.y = a.y;
// _dot.scaleX = _dot.scaleY = 1+Math.random()*3;
// _dot.alpha = Math.random()*0.5;
// addChild(_dot);
}


addEventListener(Event.ENTER_FRAME, onframe);
function onframe(evt:Event):void
{
mover(_bot);
}


First 4 lines are the same. Next we have info object to store 3 things, starting position of our bot and memory Array. Even though our memory is an Array we will use only first array element, thus our memory has only one cell.

So, inside mover we have 2 if conditional loops, where second one only returns our bot to center of the Stage if it goes out of boundaries. First if loop are instructions. First we check if bot has already moved. If it isn't then memory length is zero and we go to else branch where we choose first move.

Now, if memory cell of our bot does have some value and if that value is positive that means our bot has moved to the right in last frame. We want our bot to continue to move in same direction until it reaches Stage border. That's why we give dx only positive value. On the other hand if our memory cell have negative value, we set dx to some new negative value, so our bot can continue until it reaches left Stage border.

In other words we tell our bot to keep moving in one direction until border, then to return to center and continue in opposite direction and so on ... All this with only 1 memory cell. You can modify dy value if you want him to go more up or down.

Finally, dot MovieClip is random graphic to track bot movement and make interesting drawings. Here are some examples I've made.








Now, this is created using only one memory cell. Think of what you can do by using 10 of them or 100?

*_*

15 September 2010

Next Flash Builder "Burrito" feature [video]

'Generate from usage' feature should be part of next Flash Builder release, code name "Burrito". Watch video demonstration.



*_*

11 September 2010

Flex 4.5 SDK Hero Introduction

While Flex 4.1 build is still very hot potato (released June 30 2010), new version of Flex SDK is already here, version 4.5 code name Hero. Although final Hero release is scheduled for 2011 many interesting new features already are catching attention.

New Spark controls and containers are available and ready to use Spark Form, Spark Image, Spark Formattars, Spark DataGrid. With this Flex release Adobe has abandoned Slider, separate mobile development framework because Hero will get new mobile development capabilities.

Read more about Flex Hero features.

*_*

06 September 2010

AS3 Terminal - open source project

Nice little open source project AS3Term released by Piotr Walczyszyn. You don't need to open your Flash IDE every time you want to check small chunk of code or try something quick - use AS3Term instead.



*_*

30 August 2010

Windows-like select tool in Flash

This little select object tool can be used in games or apps. It mimics windows select tool (even colors are the same). In this example selected items have decreased alpha properties, but that action can be easily modified to suit any need.



*_*

28 August 2010

Interactive Flash Banner Game Example

Online advertising world has seen clear evolution path from text links via static and annoying dynamic banner to interactive banners and beyond. Nobody is immune to banners, advertiser have 'faith' in them, some users hate them, some find them useful. Whatever you feel about banners they are here to stay in one form or another.

With Flash, banners have introduced fun in advertising equation. But there are two kinds of Flash banners, playable and not playable ones. Not playable banners use only Flash animation power to attract visitors and in most cases users do feel deluded about the experience.

With original, not-generic playable banner you can do much more. Good advice is to give user an option (after playing the game) to click or not to click. After experiencing some new and interactive stuff, user is usually open and exited to new content and if landing page offers 'next level' of experience (or game) even better!

Here is one simple example of interactive Flash banner game. Click on letters to form a word.



Have you clicked on continue?

If you need interactive Flash banner game, contact me, I'm open for freelance work.

*_*

23 August 2010

AS3 Elevator System Simulation

I continue to rewrite older code to AS3. In April last year I posted small chunk of AS2 code needed for Elevator system simulation. This time AS3 version is much better and you can test it by yourself. Click on gray square buttons to call the elevator. While elevator is moving click on more buttons and check calling queue info.



When elevator reaches destination (callingQueue[0] element) it stops for a while; waits for people to come in :) then deletes that floor call and goes to next call. Just like in real life, at least like elevator in my building works.

Here is the code (CC license):

/*
* Elevator Simulation
* @author: http://flanture.blogspot.com
* @date: August 2010
* @license: Creative Commons Attribution-NonCommercial-ShareAlike 3.0
* ( http://creativecommons.org/licenses/by-nc-sa/3.0/ )
*/

/**
* Imports
*/

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

/**
* Variables
*/

var _numberOfFloors:uint = 6;
var _callingQueue:Array = new Array();
var _btnsArray:Array = new Array();
var _buildingGroundX:uint = 75;
var _buildingGroundY:uint = 350;
var _floorHeight:uint = 50;
var _currFloor:uint = 1;
var _waitSemaphore:Boolean = false;
var _waitCounter:int = 40;

/**
* Functions
*/

function startSimulation():void
{
currentFloorTF.text = _currFloor;
drawBuilding();
}

function drawBuilding():void
{
// add building and calling buttons
for(var i:uint = 0; i < _numberOfFloors; i++)
{
var floor:floorMC = new floorMC();
floor.x = _buildingGroundX;
floor.y = _buildingGroundY-(_floorHeight*i);
addChild(floor);

var bellBtn:bell = new bell();

// to which floor button is added
bellBtn.fn = i+1;
bellBtn.x = _buildingGroundX + 200;
bellBtn.y = _buildingGroundY-(_floorHeight*i)-10;
addChild(bellBtn);

bellBtn.addEventListener(Event.ENTER_FRAME, bellOnFrame);
function bellOnFrame(evt:Event):void
{
evt.target.stop();
}
bellBtn.addEventListener(MouseEvent.MOUSE_UP, bellOnUp);
function bellOnUp(evt:MouseEvent):void
{
if(evt.target.currentFrame == 1) {

// if elevator is working check if it can stop by
if (_callingQueue.length > 0)
{
var test:Boolean = isBetween(evt.target.fn, _currFloor,

_callingQueue[0]);

// if elevator can stop, add this floor to queue
if (test)
{
_callingQueue.splice(0, 0, evt.target.fn);
evt.target.gotoAndStop(2);
queueTF.text = _callingQueue;
} else {

var queueCounter:int = 0;
while (queueCounter < _callingQueue.length-1)
{
if (isBetween(evt.target.fn, _callingQueue

[queueCounter], _callingQueue[queueCounter+1]))
{
_callingQueue.splice

(queueCounter+1, 0, evt.target.fn);
queueCounter =

_callingQueue.length;
evt.target.gotoAndStop(2);
queueTF.text = _callingQueue;

} else {
queueCounter += 1;
}
}
if (queueCounter < _callingQueue.length)
{
_callingQueue.push(evt.target.fn);
evt.target.gotoAndStop(2);
queueTF.text = _callingQueue;
}
}
} else {

// if queue is empty add to queue if it's not same floor

if (!(evt.target.fn == _currFloor))
{
evt.target.gotoAndStop(2);

// update queue
_callingQueue.push(evt.target.fn);
queueTF.text = _callingQueue;
}
}
}
}
_btnsArray.push(bellBtn);
}

// add elevator
var elevator:elevatorMC = new elevatorMC;
elevator.x = _buildingGroundX + 50;
elevator.y = _buildingGroundY;
addChild(elevator);

elevator.addEventListener(Event.ENTER_FRAME, elevatorOnFrame);
function elevatorOnFrame(evt:Event):void
{
// if queue is not empty elevator should move
if (_callingQueue.length > 0)
{
// check if elevator needs to wait for a while
if((_waitSemaphore)&&(_waitCounter > 0))
{
_waitCounter -= 1;
if(_waitCounter == 0)
{
_waitSemaphore = false;
_waitCounter = 40;
}
} else {

// find current elevator floor
_currFloor = 1+Math.floor((_buildingGroundY-evt.target.y)/_floorHeight);

// elevator goes up
if (_callingQueue[0] > _currFloor)
{
evt.target.y -= 2;
}

// elevator goes down
if (_callingQueue[0] < _currFloor)
{
evt.target.y += 2;
}

// if elevator reached destination stop it and change variables
if (_callingQueue[0] == _currFloor)
{
if(evt.target.y < _buildingGroundY-(_currFloor-1)*_floorHeight)
{
evt.target.y += 2;
} else {
evt.target.y = _buildingGroundY-(_currFloor-1)

*_floorHeight;
var temp:uint = _callingQueue.splice(0, 1);
_btnsArray[_currFloor-1].gotoAndStop(1);
queueTF.text = _callingQueue;
_waitSemaphore = true;
}
}
currentFloorTF.text = _currFloor;
}
}
}
}

function isBetween(caller:int, currentPosition:int, destination:int):Boolean
{
if ( ( (caller < destination)&&(caller > currentPosition) )||
( (caller < currentPosition)&&(caller > destination) ) ) {
return true;
} else {
return false;
}
}

startSimulation();



Source file and additional help available via email request. I hope you find this useful.

*_*

21 August 2010

Convergence of Flash Portals and Social Gaming Slides Presentation

View more presentations from danctheduck.


*_*

18 August 2010

AS3 Random Star Field Animation

This simple function creates star field animation. You need MovieClip in your library with 'star' class linkage. If stars are not your thing, feel free to try it with any other image you make.



code ::


import flash.events.Event;
import flash.events.MouseEvent;

function starField():void {

var i:uint = 0;

while (i < 30) {
var a:star = new star();
a.x = Math.random()*400;
a.y = Math.random()*260;
var size:Number = Math.random()*40+20;
a.width = a.height = size;
a.addEventListener(Event.ADDED_TO_STAGE, getSpeed);
function getSpeed(evt:Event):void
{
evt.target.speed = Math.random()*20-10;
}

a.addEventListener(Event.ENTER_FRAME, onFrame);
function onFrame(evt:Event):void
{
evt.target.rotation += evt.target.speed;
}
addChild(a);
i++;
}
}

starField();

addEventListener(MouseEvent.MOUSE_UP, onup);
function onup(evt:MouseEvent):void
{
while(this.numChildren > 0) {
this.removeChildAt(0);
}
starField();
}


*_*

16 August 2010

How to split ActionScript Array in two or more

Until today my ActionScript Search Array functions have been downloaded 2386 times, according to Box.net counter. Despite of this number I do think every piece of code can and should be improved. That's way I'm adding new function:

splitTo(Array, int):Array

This function splits given Array to int parts. Resulting Array is two-dimensional. How it works?

Let's say you have Array of Numbers



Array a has 10 elements and you want to split this Array into 3 new Arrays. Resulting Array will return new Array as image shows.



As you can see remaining elements (in this case element 11) will be attached to last the Array. If you don't want to attach any residual elements just delete the only while loop in the code.

Here is the function:


// function splitTo splits array 'ar1' to 'parts' number of arrays

public static function splitTo(a1:Array, parts:uint):Array
{
if (parts > 1) {

var aCount:Number = a1.length / parts;
var limit:int = int(aCount);
var res:Array = new Array();

// if aCount <= 1
if (aCount <= 1)
{

// put every element in new array
for (var i:uint = 0; i<a1.length; i++)
{

// make new array and resulting array
var newarray:Array = new Array();
newarray.push(a1[i]);
res.push(newarray);
}
} else {
for (var k:uint = 0; k<parts; k++)
{
var newarray2:Array = new Array();

if (a1.length > 0)
{

// if a1 is not empty
for (var j:uint = 0; j<limit; j++)
{
newarray2.push(a1.splice(0, 1));
}
res.push(newarray2);
}
}

// put rest of the elements inside last array
while (a1.length > 0)
{
res[res.length-1].push(a1.splice(0, 1));
}
}

// return resulting Array of Array[s]
return res;
} else {
return a1;
}
}


More similar functions coming soon.
Stay updated by subscribing to blog RSS feed, or follow me on Twitter.
Thanks for sharing.

*_*

11 August 2010

Flash Comics Album version 2.0

First steps with Flash Comics Album were taken back in May 2007. Right now, I'm moving all my previously done stuff towards AS3 version and if it is possible improvements will be included also. If you wanna read more, here are all previous posts about Comic Album.

1) Comic Album Flash application
2) project reactivated
3) Good Ideas and Clumsy Efforts

Comic Album v2.0 is intended for comic/strip artists who want to present their work on the web. Application reads external assets and they include configuration XML file and images. Main feature of Comic Album is it allows you to present comic in two modes, with and without text bubbles. This is why every comic scene comes with two images. One image is scene itself and can be jpg, gif, png and second image is transparent png which presents only text.

User can turn text on/off, enjoy whole thing or only look at images. Example file use fixed size 400x300 pixels images, but on request this can be altered.


How to use Comics Album 2.0

First, you need to download example files to your computer. Replace images inside assets folder with your own images. Then open comic.xml file with any text editor. Change 'scene' and 'txt' attributes of page tags to correspond to your files names. Upload swf and assets folder to your website and embed into desired page.


If you need different size album, some extra features or you have suggestions how to improve this version, feel free to comment or send me e-mail. This version doesn't include error checking code, so you have to be careful to have proper xml file and images. Also, idea is to have small images, few Kb per image, so album doesn't come with preloaders.

*_*

09 August 2010

Flash Tutorial : How to create vertigo animation

There are many situations where interesting Flash animations can be applied, in games, flash widgets, as website effect etc. Some animations require slow frame-by-frame making process and some can be created quickly using free community shared tools.

Spiral tool can be found on author's website. After you download it and install it, you can take a look how this tool is created by opening your Flash Configuration folder. On Windows this folder should be located at C:\Documents and Settings\Administrator\Local Settings\Application Data\Adobe\Flash CS3\en\Configuration\Tools. Among others you will find files: Spiral.xml, Spiral.png and Spiral.jsfl. Simply open Spiral.jsfl with your favorite text editor to see Spiral tool source code.

You can use newly installed Spiral tool directly from Tools panel (see image below).

Flash Spiral Tool
When you are satisfied with spiral you created convert it to movie clip and add simple rotation code to it:

import flash.events.Event;

addEventListener(Event.ENTER_FRAME, rotate);
function rotate(evt:Event):void
{
rotation += 5;
}

Click on image to see live demo.



That's just a starting point. You can go further and make all kinds of complex vertigo animations. Simple adjustments would be to change drawing line size, style and color. Combine few different spiral lines with different rotation speeds to get even more complex vertigo.

*_*

07 August 2010

Indie Games Development - Solo vs Team

In the latest July 2010 issue number 107 of [games] develop magazine, Sophie Houlden speaks about her way into indie game development. Article titled "You can do it" starts with: "Sophie Houlden hasn’t spent a penny on tools to make her indie games – she just rolled up her sleeves and got on with it". Inspiring story.

However, I don't think that's the right way to do it. Few of us went there and never returned. Making it on your own can have just a few positive consequences, ego tripping is one. Financial gain? Hardly. Chances for you to make good money as one-man-team developer are so small, you'll be better off playing lottery.

But main loss is learning. Fact is - you will learn much more in a team about tools, code practices and everything else than by doing it by yourself. I don't even want to mention importance of being around other people during those long hours ... What can you learn by taking solo project except for how to take more solo projects?

I don't have anything against indie games development, quite opposite, but my advice is always work in a team. Why? Well, if project doesn't succeed, at least you had your fun - and you do have fun while making games, right?

*_*

02 August 2010

Good Ideas and Clumsy Efforts

Summer vacation is over. This one was longer than usual which translated to single post in July, lowest number of posts per month in 3+ years of blogging. However, good side is, it allowed me to clearly observe entire blog experience and pinpoint new goals and directions.

One thing I found is some older projects need to be rewritten. There were some great ideas and clumsy efforts to make things work. Few of those will get back to life in weeks and months ahead.

I'll start with Comics Album, previously written in AS2, some 3 years ago. Here are two posts about it:

1) Comics Album Flash App
2) project reactivated

This time it's all about AS3 code. Here is screen preview of Comics Album version 2.0 (work in progress).

comics album flash application preview


*_*

01 July 2010

Simple AS3 Data Structure - part II

Student data structure from previous post doesn't have to be created like I have shown earlier. There is one more OOP way of doing it, to create a class. Private variables will hold particular information and we can use getters and setters to assign and retrieve values.

Here is the code for Student.as class:



package
{
public class Student
{
private var _name:String;
private var _age:uint;
private var _grades:Array;

public function Student (sName:String):void
{
_name = sName;
}

public function set name (studentName:String):void
{
_name = studentName;
}

public function get name ():String
{
return _name;
}
public function set age (studentAge:uint):void
{
_age = studentAge;
}

public function get age ():uint
{
return _age;
}

public function set grades (studentGrades:Array):void
{
_grades = studentGrades;
}

public function get grades ():Array
{
return _grades;
}

public function getAverage():Number
{
var sum:Number = 0;
for (var j:uint = 0; j < grades.length; j++) {
sum = sum + grades[j];
}
return sum / grades.length;
}
}
}



As you may noticed there is built-in getAverage function to make things easier. Now, you can test this class functionallity by creating TestStudent.fla in same directory where you saved Student.as file. In first frame of the TestStudent file enter next code:



import Student;

var student1:Student = new Student("John");
student1.age = 22;
student1.grades = [4, 5, 5, 3];

var student2:Student = new Student("Ella");
student2.age = 20;
student2.grades = [4, 5, 5, 4, 5];

var average:Number = student1.getAverage();
trace(average);

average = student2.getAverage();
trace(average);



Which method you will use depends on your needs and style.

*_*

24 June 2010

Simple AS3 Data Structure

In ActionScript 3 Arrays play very important role. This is powerfull class for storing and manipulating different type of values. If I have only one type of data, for example, only Strings, I will use Vector class which is almost exaclty like Array class, but it can store one data type only. Simple Array with different data types would be created like this:



var student = new Array();
student[0] = "John";
student[1] = 22;
student[2] = "Elle";
student[3] = 21;



Here I have strings representing names of students and numbers representing their age. I can trace all info at once with a loop:



for (var i:uint = 0; i<student.length; i++) {
trace("info : "+student[i]);
}



Since my collection of data have clear "units" where single unit holds data for single student I need to structure data differently so I can take advantage of language for easier data manipulation. In this particular case indexed array is fine, but in some other cases it will be better and more efficient to use associative arrays or not use arrays at all.

For this example I'm using Objects to store data about students, one Object per student. Simplified example would look something like this:


var st1 = new Object();
st1.name = "John";
st1.age = 22;
st1.grades = [5, 4, 4, 3, 5, 3];


Now I have my data structured like image shows.



When data is structured like this it's easy to trace info and manipulate data. This example finds average grade for every student in students Array and outputs info for every student.


var students = new Array();

var st1 = new Object();
st1.name = "John";
st1.age = 22;
st1.grades = [5, 4, 4, 3, 5, 3];
students.push(st1);

var st2 = new Object();
st2.name = "Ella";
st2.age = 20;
st2.grades = [4, 5, 5, 4, 5];
students.push(st2);

for(var i:uint = 0; i < students.length; i++) {
trace((i+1)+".");
trace("NAME : "+students[i]["name"]);
trace("AGE : "+students[i]["age"]);
trace("grades : "+students[i]["grades"]);
var temp:Number = getAverage(students[i]);
trace("average grade :: "+temp);
trace("");
}

function getAverage(o:Object):Number
{
var sum:Number = 0;
for (var j:uint = 0; j < o.grades.length; j++) {
sum = sum + o.grades[j];
}
return sum / o.grades.length;
}



You can use Array class methods to add new students // students.push(st3) // or remove them from array with splice. To remove John use // students.splice(0,1);

*_*

15 June 2010

Free FFD magazine June issue


Since Flash & Flex Developer's Magazine started with monthly editions I can't read the whole issue and another one is already out! I'm not complaining, quite the opposite. If you're not familiar with it, I recommend you take a look at only FREE Flash related magazine. Here is short content of June issue.

  • Lee Graham writes about Flash Player 10.1 on Android and AIR for Android.
  • Louis DiCarro has Flash and the City 2010 review, three days presentations event held in New York from 13th until 16th May.
  • Huw Collingbourne writes about the Flash Platform in Visual Studio. The Amethyst IDE lets you edit, design and debug Flash, Flex and AIR applications ...
  • You can also read interesting story about validating your skills and best practices with the Adobe Certified Associate Exam by Sinead Hogan.
  • In ActionScript Development section find out how to use Flash Builder 4 to code Flash CS5 projects, another one by Louis DiCarro.
  • In Flex Development awaits part II of XML Photo Gallery Tutorial written by Ryan D'agostino.
This is not entire content! Visit FFmag and download latest June issue.

*_*

01 June 2010

How to use transparent Flash widget

One interesting aspect of using Flash widgets on web pages is transparency. In some situations it's good to leave background behind transparent Flash widget as it is to get floating, natural effect. Widget will look almost as part of your template except it can react to mouse movements and/or include some interesting animation.

You can also take advantage of transparent Flash widget by including background image right into your HTML tag which embeds Flash file. Take a look at recently published Office Transparent Flash Clock at my Flash2nd blog. Here are some suggestions how you can use this widget.



In this way you are no longer passive user, you participate and improve existing Flash widget by giving it personal, customized touch.

images by: source 1, source 2.

*_*

22 May 2010

Using BitmapSplit function with Tweener

Few posts ago I introduced Dynamic Bitmap Split Function. This function allows you to split any Bitmap into any (reasonable) number of column and rows and use those parts separately.

Here is one quick example of using this function together with Tweener class. Click on image to see live example.



and here is code:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.utils.ByteArray;
import flash.geom.Rectangle;
import flash.events.Event;
import caurina.transitions.*;

var bmd1:BitmapData = new BitmapData(100, 100, false, 0x666666);
var bm1:Bitmap = new Bitmap(bmd1);
bm1.x = 120;
bm1.y = 100;
addChild(bm1);
var expand:Boolean = false;
var bitmapsArray:Array = new Array();

addEventListener(Event.ENTER_FRAME, onFrame);

function onFrame(evt:Event):void
{
if(expand)
{
bm1.alpha = 0;
for(var k:uint = 0; k < bitmapsArray.length; k++)
{
var curr:uint = bitmapsArray[k].length;

for(var l:uint = 0; l < curr; l++)
{
Tweener.addTween(bitmapsArray[k][l],
{x:20*l+10, y:33*k+10, alpha:0.5, time:3, transition:"linear"});
expand = false;
}
}
}
}

function splitBitmap(_source:BitmapData, _columns:int, _rows:int):void
{
var _bitmapWidth:int = _source.width;
var _bitmapHeight:int = _source.height;

var _onePieceWidth:Number = Math.round(_bitmapWidth / _columns);
var _onePieceHeight:Number = Math.round(_bitmapWidth / _rows);

var _copyRect:Rectangle = new Rectangle(0, 0, _onePieceWidth, _onePieceHeight);
for(var i:int = 0; i < _columns; i++)
{
var tempArray:Array = new Array();

for(var j:int = 0; j < _rows; j++)
{
var _piece:String = "piece"+String(i)+String(j);
var temp:* = [_piece];
temp = new BitmapData(_onePieceWidth, _onePieceHeight, true, 0xFF0000CC);

var newBytes:ByteArray = _source.getPixels(_copyRect);
newBytes.position = 0;
temp.setPixels(_copyRect, newBytes);

var _newBitmap:String = "newBitmap"+String(i)+String(j);
var tempBitmap:* = [_newBitmap];
tempBitmap = new Bitmap(temp);

tempBitmap.x = i * (_onePieceWidth) + bm1.x;
tempBitmap.y = j * (_onePieceHeight)+ bm1.y;
addChild(tempBitmap);

tempArray.push(tempBitmap);
}
bitmapsArray.push(tempArray);
}
expand = true;
}

splitBitmap(bmd1, 5, 3);


more examples to come.

*_*

20 May 2010

How to start with PaperVision3D

While searching for some instructions on how to start with PaperVision3D for complete idiots there were few very good and few outdated places. One very detailed set of tutorials starting with Papervision 3D Programming Tutorial written in September 2009 doesn't work with Flex 4 SDK, but requires older compiler version or changing some of the code provided.

Getting Started with PaperVision3D

Most useful tutorial I found on downloading and installing PaperVision3D came from YouTube. This 9 minutes video is walk-through of how to find and install Tortoise SVN, how to use it to download PaperVision3D files and how to start new Flex project using those files.



Video is narated by Amanda V. from Northern Kentucky University, Office of Instructional Design.

Another option is to setup Papervision3D in FlashDevelop and explore some cool PaperVision3D examples . Feel free to share a link or two with PaperVision3D Tutorials. Thanks.

*_*

17 May 2010

Adobe AIR + Flash on Android

Android platform developers have only a few days left until Google's largest developer event of the year, I/O Conference in San Francisco May 19-20. They announced 80 sessions, more than 3000 developers and over 100 demonstrations including AIR and Flash on Android.

Mobile devices developing has never been this exciting and Android 2.2 (FroYo) is the latest wanna-rule technology.


image by tomsun

*_*

07 May 2010

Enter your choice now: Adobe or Apple?

There's a war out there and the end of it is far beyond horizon. Wounded developers soldiers on both sides, waiting for next battle while Generals are drinking wine somewhere in the castle tower and looking at the battlefield plans. Off course, everyone knows that war is pointless, but ... wait, what? You don't?

o Thoughts on Flash by Steve Jobs
o On Adobe, Flash CS5 and iPhone Applications by Mike Chambers
o Is Flash Dead Yet? by Scott Schiller
o The iPad provides the ultimate browsing experience? by Lee Brimelow

Main question is why this clash happened at first place and who is target audience: consumers, businesses or developers? So, what are they saying if asked to choose between Adobe or Apple:

- consumers - I don't care, but it must be cool
- businesses - I don't care, but it must work
- developers - I do care, but I'm not 100% sure why :)

My choice? Google.

There is no choice, only toilet paper.

*_*

03 May 2010

AS3: Dynamic Bitmap Split Function

Recently I had most rewarding moments while playing around with Bitmap and BitmapData classes in ActionScript3.0 and also I must mention how this becomes more fun than really learning the language.

While reading about copying pixels from one Bitmap to another this idea fall into my mind about writing function to allow me to split any loaded or drawn image into desired number of columns and rows. Solution was quite easy actually, with a little help of ByteArray class.

Here is the function which allows you to do just that, dynamic split of any image:


function splitBitmap(_source:BitmapData, _columns:int, _rows:int):void
{
var _bitmapWidth:int = _source.width;
var _bitmapHeight:int = _source.height;

var _onePieceWidth:Number = Math.round(_bitmapWidth / _columns);
var _onePieceHeight:Number = Math.round(_bitmapWidth / _rows);

var _copyRect:Rectangle = new Rectangle(0, 0, _onePieceWidth, _onePieceHeight);
for(var i:int = 0; i < _columns; i++)
{
var tempArray:Array = new Array();

for(var j:int = 0; j < _rows; j++)
{
var _piece:String = "piece"+String(i)+String(j);
var temp:* = [_piece];
temp = new BitmapData(_onePieceWidth, _onePieceHeight, true, 0xFF0000CC);

var newBytes:ByteArray = _source.getPixels(_copyRect);
newBytes.position = 0;
temp.setPixels(_copyRect, newBytes);

var _newBitmap:String = "newBitmap"+String(i)+String(j);
var tempBitmap:* = [_newBitmap];
tempBitmap = new Bitmap(temp);

tempBitmap.x = i * (_onePieceWidth) + bm1.x;
tempBitmap.y = j * (_onePieceHeight)+ bm1.y;
addChild(tempBitmap);

tempArray.push(tempBitmap);
}
bitmapsArray.push(tempArray);
}
}


Setting tempBitmap x and y properties is optional, because I wanted to put new pieces in original place (above bm1, original Bitmap) so viewer can't see these are new

DisplayObjects. In this way transition effect is masked. You may also notice bitmapsArray, two-dimensional Array to hold all pieces in one place for later easy manipulation.

There can be some improvements to it, like limiting max number of columns and rows or adding image import with Loader class etc. but main functionality is there, working like a charm. Now, you can use this function to produce all kinds of transition effects and image manipulations. Some examples might follow in future posts.

*_*

28 April 2010

Running Flex 4 SDK and FlashDevelop

Using only Flash IDE for ActionScript or AIR projects is almost never final choice for many developers. In fact, majority of developers use all kind of available tools. When team work is involved usable knowledge of these tools is a must and this is also a big plus in anyone's portfolio. Here is small intro how to introduce Flex 4 SDK + FlashDevelop workflow.

First of all go and download Flex 4 SDK from Adobe Opensource Pages. Install downloaded files somewhere on your hard drive C:\flex4sdk for example. Set path to this folder. Right click on My Computer icon, go to Advanced tab and click on Environment Variables. In System variables list choose path, click edit and add path to newly created folder to the end of line. Go to Command Prompt and test your work with compc -version command.

You will also need FlashDevelop from their site, downloaded and installed. I have 3.0.6 RTM running, but more recent version is now available. Simple HelloWorld AS3 Project is enough to see if everything is OK.

I got following error after I tried to compile my project: 'C:\Documents and Settings\[USER]\My Documents\FDProjects\HelloWorld\HelloWorld.as: Warning: This compilation unit did not have a factoryClass specified in Frame metadata to load the configured runtime shared libraries. To compile without runtime shared libraries either set the -static-link-runtime-shared-libraries option to true or remove the -runtime-shared-libraries option.'

In order to solve this problem, right click on project name, open Properties and choose Compiler Options. Within Additional Compiler Options add this line: -static-link-runtime-shared-libraries=true (see image). This will solve warning issue.

setting flex compiler advanced options
One more thing. I highly recommend using Senocular's pseudo output panel for testing purposes.

So, there you have it, basic setup of Flex 4 SDK and FlashDevelop. If you like this post leave comment or share. Thanks.

*_*

19 April 2010

New Flash Games development job

Totally unexpected opportunity knocked on my door few days ago and I'm still thinking if I should take it or not. A friend of a friend of a friend of mine offered me to make few small Flash games for kids. He is into publishing business, mostly educational books for children under 7-8 years old and they want to expand to multimedia educational games. My job would be coding and animating since they already have ideas and graphics ready.

I found inspiration via these Flash educational games links, lots of interesting examples are available. Just recently I have started to learn more about Flash Games development and this call came just on time, but I'm still not sure if I could pull it off. I have explained them about my short experience in subject but after they looked at this blog, they are more confident in me then myself.

Do you have any experience in the subject or/and can point me to some examples? Thanks.

*_*

13 April 2010

Random Generator updated to AS3

If you are blogger, are you happy to see your older posts are still read and commented, even years has past? I am. Especially if I see ppl are using my older code for learning. That's why I updated AS2 Random Number Generator to AS3 version.

There is one new getRan function which return random number less than max parameter. You can use this to limit the number you want to display. Here is new code with minor changes.


// author: FLANTURE http://flanture.blogspot.com
// date: 24 Jan 2009
// updated: 13 Apr 2010 (AS2 -> AS3)

import flash.filters.BlurFilter;
import flash.events.Event;
import flash.text.TextField;

var timerStarted:Boolean = false;
var counter:uint = 0;
var firstDigitStop:uint = 8;
var secondDigitStop:uint = 16;
var thirdDigitStop:uint = 20;
var filter:BlurFilter = new BlurFilter();
var filterArray:Array = new Array();

// function for roll_mc movie clip onPress action. If timer has not started,
// that means there is no action in progress, so we can start one.

roll_mc.addEventListener(MouseEvent.MOUSE_UP, onRoll);
function onRoll(evt:Event):void
{
if (!timerStarted) {
var filter:BlurFilter = new BlurFilter(60, 120, 1);
var filterArray:Array = new Array();
filterArray.push(filter);

num1_txt.filters = filterArray;
var newNumber1:Number = getRan(10);
num1_txt.text = newNumber1;

num2_txt.filters = filterArray;
var newNumber2:Number = getRan(10);
num2_txt.text = newNumber2;

num3_txt.filters = filterArray;
var newNumber3:Number = getRan(10);
num3_txt.text = newNumber3;

timerStarted = true;
}
}

// functions for restoring blur effect

function restoreBlur1() {
num1_txt.filters = new Array(filter);
}
function restoreBlur2() {
num2_txt.filters = new Array(filter);
}
function restoreBlur3() {
filter.blurY = 0;
filter.blurX = 0;
num3_txt.filters = new Array(filter);
}

// next function controls when blur should stop and numbers should display.

addEventListener(Event.ENTER_FRAME, onFrame);
function onFrame(evt:Event):void
{
if (timerStarted) {
if (counter < thirdDigitStop) {
counter += 1;
if (counter == firstDigitStop) {
restoreBlur3();
}
if (counter == secondDigitStop) {
restoreBlur2();
}
} else {
timerStarted = false;
counter = 0;
restoreBlur1();
}
}
}

// you can change firstDigitStop and other variables to suit your needs.
// numbers represent frames, not seconds.

function getRan(max:uint):uint
{
return Math.floor(Math.random()*max);
}



Everything else is the same, just target at least Flash Player 9 with AS3.



*_*

06 April 2010

AS3 Spiderweb Workshop

If you have read about improved spiderweb AS3 class here is a little tool I made to make things easier. This visual toy will allow you to create your own spiderweb fast.

Right now, there isn't size limit, so your creation will go out of borders if not appropriate parameters are used. In some future version I'll include size limit plus I'll add maybe save feature. Stay tuned. Share if you find it interesting.


Click on image to download spiderweb workshop utility which is only 3Kb.

*_*

29 March 2010

SearchArray AS3 functions class renamed and updated

Three months ago, back in January I have added one more function to popular my SearchArray AS3 Class. Now, I'm introducing three more functions to it but since functions are not search related now this Class have more general purpose, so I needed to rename it to ArraysUtil Class.

New functions are:

- public static function unique(arr:Array):Array
This function returns new Array with elements of given arr Array appearing just once. If arr = [1, 3, 5, 3, 5], new Array will be [1, 3, 5].

- public static function exclude(elem:Object, arr:Array):Array
This function returns new Array from elements of old arr Array without element elem.

- public static function excludeAll(ar1:Array, ar2:Array):Array
This function works like previous exclude function except it removes multiple elements from old Array

Here is class code with example usage:


package com.blogspot.flanture.arrays
{

// ArraysUtil AS3 functions
// author: http://flanture.blogspot.com
// license: Creative Commons Attribution-Share Alike 3.0
// http://creativecommons.org/licenses/by-sa/3.0/
// contact: flanture@gmail.com
// March 2010

import flash.display.Sprite;

public class ArraysUtil extends Sprite
{

public function ArraysUtil()
{

// example usage

var a:Array = [1,2,3,5,3];
var b:Array = [2,4,6,8];
var c:Array = [1,2,3,5,3];
var d:Array = [5,7,9,5,5,7,5,7,9];
var e:Array = [5,5,9];
var f:Array = [5,7,9,5,5,7,5,7,9];
trace("array a: "+a);
trace("array b: "+b);
trace("array c: "+c);
trace("array d: "+d);
trace("array e: "+e);
trace("array f: "+f);
trace("* * * * *");
trace("is there element 6 inside array b?");
search(6, b);
trace("a combined with b: "+combine(a,b));
trace("6 exists in b? "+searchB(6,b));
trace("number of 3 in a? "+searchCount(3,a));
trace("intersection of a and b: "+iSection(a,b));
trace("shuffled b: "+shuffle(b));
trace("exclude element 3 from array c : "+exclude(3,c));
trace("exclude all array e elements from array d :"+excludeAll(e, d));
trace("unique of f :"+unique(f));
}

// function search finds element in array and displays result

public static function search(word:Object, arr:Array):void
{
var exists:Boolean = false;
for(var i:uint=0; i < arr.length; i++)
{
if(arr[i]==word)
{
trace("Element exist on position "+i);
exists = true;
}
}
if(!(exists))
{
trace("Element doesn't exist in array.");
}
}

// function searchB finds element in array and returns Boolean value

public static function searchB(word:Object, arr:Array):Boolean
{
var exists:Boolean = false;
for(var i:uint=0; i < arr.length; i++)
{
if(arr[i]==word)
{
exists = true;
}
}
return exists;
}

// function searchCount returns number of apperances of element in array

public static function searchCount(word:Object, arr:Array):uint
{
var counter:uint = 0;
for(var i:uint=0; i < arr.length; i++)
{
if(arr[i]==word){
counter+=1;
}
}
return counter;
}

// function iSection returns intersection array of two arrays

public static function iSection(arr1:Array, arr2:Array):Array
{
var arr3:Array = new Array();
var count:uint = 0;
for(var i:uint=0; i < arr1.length; i++)
{
for(var j:uint=0; j < arr2.length; j++)
{
if(arr1[i]==arr2[j])
{
arr3[count] = arr1[i];
count+=1;
}
}
}
return arr3;
}

// function shuffle simply shuffles given array elements

public static function shuffle(b:Array):Array
{
var temp:Array = new Array();
var templen:uint;
var take:uint;
while (b.length > 0)
{
take = Math.floor(Math.random()*b.length);
templen = temp.push(b[take]);
b.splice(take,1);
}
return temp;
}

// function combine returns union of two arrays

public static function combine(ar1:Array, ar2:Array):Array
{
var rAr:Array = new Array();
var i:uint = 0;
var j:uint = 0;

while((i < ar1.length) || (j < ar2.length))
{
if(i < ar1.length)
{
rAr.push(ar1[i]);
i+=1;
}
if(j < ar2.length)
{
rAr.push(ar2[j]);
j+=1;
}
}
return rAr;
}

// function exclude remove all appearances of element inside given array

public static function exclude(elem:Object, arr:Array):Array
{
var temp:Array = new Array();

for(var i:uint = 0; i < arr.length; i++)
{
if(!(arr[i]==elem))
{
temp.push(arr[i]);
}
}
return temp;
}

// function excludeAll remove all appearances of ar1 elements inside ar2 array

public static function excludeAll(ar1:Array, ar2:Array):Array
{
var temp:Array = new Array();
ar1 = unique(ar1);

while(ar2.length > 0)
{
if(searchCount(ar2[0], ar1) == 0)
{
temp.push(ar2[0]);
}
ar2.splice(0, 1);
}
return temp;
}

public static function unique(arr:Array):Array
{
var res:Array = new Array();

while(arr.length > 0)
{
if(searchCount(arr[0], arr) == 1)
{
res.push(arr[0]);
}
arr.splice(0,1);
}
return res;
}
}
}



Class has 9 functions right now, I'll add some more later. If you have any questions about the code don't hesitate to ask.

*_*

 

template by blogger templates