Stroep

Just a collection of random works – Mark Knol

Archive for 'Actionscript'

Particle test center (5)

December 29th, 2009, under Actionscript.

For a while now, I am experimenting with this new experiment. I created an algorithm with nested sinus/cosinus, to show of some cool 3d looking particles (no there is no 3d in it). It is amazing to see how many particles flash can move. I used components from bit-101 to have some interaction.

Check: http://projects.stroep.nl/particles/

ChainI created a useful util-class to make delayed function calling easy. You can make a chain of functions, by adding them with a delay in milliseconds. This chain can be executed multiple times, even in reversed order.

Let’s take a look at a simple example of Chain.

var myChain:Chain = new Chain();   
myChain.addEventListener( Event.COMPLETE, onComplete);
myChain.add(one, 2000).add(two, 500).add(three, 1000).play(2);

function one():void { trace("one") }
function two():void { trace("two") }
function three():void { trace("three") }
function onComplete(e:Event):void { trace("done.") }

/* trace output:
one two three one two three done.
*/

 

What is happening here? At the first line we are instantiating the class, and the second line represents what chain does. There is a public function called ‘add’, which is an important part of the class. add(one, 2000) means: execute a function called ‘one’ after 2000 milliseconds. add(two,500).add(three,1000) are functions that are called after one is finished, with other delays. You can create your own rhythm/sequence/pattern. At the end we see play(2), which means: Execute the sequence of functions defined before, and repeat them 2 times. After that, dispatch event COMPLETE.

So that’s basically it. A cool part is you can play it reversed, using playReversed(). I am inspired by jQuery (which has nothing to do with this) to enable the ability to stick functions, but thats optional.

myChain.playReversed(2);

/* trace output:
three two one three two one
*/

 

Of course you can pauze/continue when you are playing, by calling stop() / doContinue(), and you can determine if it is currently playing using the isPlaying-getter.

These are all the public functions.

/// Constructor
public function Chain()

/// Adds a function at a specified interval (in milliseconds).
public function add(func:Function, delay:Number = 0):Chain

/// Start playing the sequence and calling functions
public function play(repeatCount:int = 0):void

/// Start playing the sequence reversed
public function playReversed(repeatCount:int = 0):void

/// Clears sequence list. Data will be removed.
public function clear():Chain

/// Stop playing, use doContinue to play futher from current point
public function stop():void

/// Continue playing after a stop
public function doContinue():Chain

/// Reset indexes
public function reset():void

/// Returns the string representation of the Chain private vars.
public function toString():String

/// Return chain is playing, stopped or completed
public function get isPlaying():Boolean
 

Hope you like it, let me know if you like to see extra/other related features.

Download: Chain (googlecode)

Updates
- Private functions are protected
- add-functions is now add(function, delay), where function is required.
- Class now extends EventDispatcher and play/playReversed dispatches Event.COMPLETE after playing sequence, instead of calling onComplete function
- Cleaned up code

Tagged with , , , .

I’ve updated my Image class. It is irritating flashsites break the right-click contextmenu. Well, I can’t fix that and Adobe should look at that, but I think it would nice to add some of the browser – features to my image class.

Currently I have these options added to the Image class:

View image
Views image in new window/tab. I used NavigateToURL to make this happen.

Save Image as..
Saves image on your computer. I used my ImageClass.saveLocal() to make this happen. This is only available within FP10, but I think this is no problem anymore because < a href = "http://www.adobe.com/products/player_census/flashplayer/version_penetration.html" > 93 % (September 2009) has FlashPlayer 10, so most people have it, and I don’t support outdated software ;)

Copy Image location
Copies the url to the clipboard, using System.setClipboard(url). It’s a pity I can’t create a ‘Copy Image’ function, because pushing bitmapdata into the clipboard is only supported in AIR.

Send Image
Sends the url to the mail-client, using “mailto:&body=” + src. Also a pity; I can’t add the image directly into the mail.

How to enable the contextmenu:

import nl.stroep.utils.Image;

var myImage:Image = new Image("myImage.jpg");
myImage.enableContextMenu = true; // enable it!
this.addChild(myImage);
 

I still love this class, I use it a lot. I want to encourage you to please add these kind of usability things to your apps / websites. And share them! Yes, it takes some extra time to create/add it, because this IS the finishing touch, but a lot of people will like this kind of features.

Download
Check out the Image class atgooglecode

Tagged with , , , .

Code snippetI found out the getBounds()-function gives not exactly the right rectangle with a TextField. It always matches the border bounds, even if the borders are invisible. So I’ve created a more accurate function using getColorBoundsRect().

Click on the words. Switch between getRect() and getTextFieldBounds() by clicking on the buttons below to see the difference.

» Download source

Tagged with , , .

Square rootFound out something useful, which I’d like to share with you. It’s about calculating the width of menu-items perfectly.

Imaging you are creating a liquid website with a menu. If you want all items to have the same width, you could set the width of each item to totalMenuWidth / items.length. In most cases this will work out. But what is your menu is very small or the items doesn’t fit in that fixed width because the text is too long?

Well you could hardcode the width’s to make your own perfect proportions and spacing, but if your menu is xml-driven and you/someone else adds new menu-items, you have to re-assign the hardcoded widths and you feel unhappy :) Most hardcoded stuff is evil anyway because it is laziness. (I use it a lot :P )

Well, I’d like to calculate the perfect scaling menu, so I don’t have to worry the menu will break. You can use the text-length of the menu-item as input for the width calculation. The more letters, the bigger the menu-item, right? So, If you multiply all menu-text-lengths and divide this to the current text-length, you’ll get a ratio which can be divided from the total menu width. I like this theory. So we need to do this in 2 steps; first get the ratios and get the total menu-text-lengths (with a loop), then calculate and apply this on each item.
Pseudocode:

itemwidth = fullMenuWidth / (totalTextLength / menuitem.text.length)

This works fine, and its actually very cool. Now we have a function which actually use some proportions to create a liquid menu. After a while I realized that the proportions weren’t really right. If the menu text have odd text-length differences (eg 5 letters vs 25 letters), it looks weird. Larger texts take too much width. I wanted the same proportions kinda like a html-table.

So the menu-items needs to have better proportions. Bigger text should be a smaller and the smaller text should be bigger. After some searching I ‘discovered’ Square root, a.k.a. Math.sqrt() in actionscript. With this function you could ‘normalize’ numbers. Bigger numbers are getting smaller, smaller numbers are getting bigger. This was exactly what I needed!

You can see the result below:

[kml_flashembed publishmethod="static" fversion="9.0.0" movie="http://projects.stroep.nl/PerfectWidth/PerfectWidth.swf" width="100%" height="235" targetclass="flashmovie" wmode="transparent"]

Get Adobe Flash player

[/kml_flashembed]

You can see the differences between the menubars and you’ll agree to me that the last one is the best :) I think this theory could be applied to a lot more things, like graphs or grids.

In case anyone is interested in the code; it can be downloaded here (AS3).

Tagged with , , .

Actionscript to vector graphicI like to generate art and objects with Flash/actionscript. Mostly I use a bitmapdata for that and export this as a PNG-24. This works perfect in most cases. But sometimes I wish there was a simple way to export my art to a scalable vector graphic. This would save a lot of data, and I’ll be able to create unlimited large and sharp prints.

I started searching and found some nice-to-know options.

Save as PDF
If you have a PDF-printer installed, you could save the vectors as PDF (drawed with lineTo, curveTo etc). Just right-click on your flashmovie, and choose ‘print..‘. Then choose ‘Adobe PDF‘ or another PDF printer. This is very simple!
Downside; My flash movie is becoming very slow when I create a lot of shapes.. After all; That’s the reason I use BitmapData objects. Sometimes I let Flash render a whole night before saving it and maybe it create more then a million shapes. To be realistic; I think a million shapes wouldn’t be cool as vector graphic, I guess my Illustrator doesn’t like that or the printshop-dude starts crying ;) However.. I think there are tools to optimize/clean shapes that could be helpful too.

Open vector formats
I didn’t know this exist (because I never searched for something like this), but there is a lot information about a SVG file format. A lot of vector programs support it already and even modern browser could show SVG file formats too.
I found this and this link. The opposite would be an great idea; It could be cool if we could export SVG. While rendering we could write/add into a file. Then I could use a small bitmapdata object, just show it and render it real-time. Downside; I think SVG doesn’t support blendmodes or filters.

I really think there is a lot more to explore. If anyone have some other suggestions or ideas, feel free to post it.

Tagged with , , , .

Game – block.game (3)

July 31st, 2009, under Actionscript, Games.

block.game

Introduction

AS3 puzzle block game. Just for fun I created this puzzle-game. It is not very innovative, but it’s cool (and a little bit hard) to explore how to build this kind of game.  Don’t know the exact name for this game, so I called it block.game ;)

How to play

Click on groups of the same color. The bigger group, the more score. You get a message when no moves can be done, or when the board is empty.

How I created it – braindump

I’ve learned you need to think twice before starting coding. This game had some really challenges in it.

Challenge 1:
I know what you are thinking; the map is just an array. Well; that’s true. A challenge while creating the game was to find out what a left or right side in the game was. My array doesn’t know what rows are, because I choose to not use a multidimensional one. So I created a way to calculate what a row was. I used modulo for this. Take a look at this code to see how easy the problem could be fixed. It just took me a long time to get to this point, I guess. :)

if ( index % mapWidth == 0 ) { // left side of board }
if ( index % mapWidth == mapWidth ) { // right side of board }
 

Conclusion: Modulo makes live easy. We need to use it more.

Challenge 2:
How to find all blocks around the active block? It loops around the active block to see if they had the same type (=color). If not; stop looping. If it does; repeat function from that point again with exception below the imaginary boundaries created in challenge 1. Well, this is a typical example to use recursive loops; I used it for this. Recursive programming is a bit hard to understand if you don’t work a lot with them. My conclusion: Learning recursive function is cool.

Challenge 3:
When you clear a column, the column should move to the left, right? I thought that would be very easy; just move all columns after the newest empty column just one position to the left and that’s it.
But it wasn’t that easy. I needed to loop through all the columns after the empty one, and push it them the left. But.. At the right side of the board there are empty columns too (if you clicked a empty row before). So Flash was thinking; Cool I’ve found some empty rows at the right side of the board. Yeah; put more to the left. :) But there wasn’t more, because the column before the last empty column at the right side is the last one (you still get me?). Flash was recursively looping and after 15 seconds he gave up.. an infinite never ending loop. Conclusion; I needed to calculate the last not-empty-column first. Then find the empty columns between the first empty column in the middle of the board and the calculated not-empty-column. If found it; move that columns one position to the left.

I hope you like the game. I haven’t implemented a highscore (yet).

Code will be available soon on flashden.

Play @ games.stroep.nl
Buy source @ flashden.net

Tagged with , , , .