Stroep

Just a collection of random works – Mark Knol

Tag Archives: snippet

Quick post here. I’d like to share this very quick way to create an automatic ID or index to your class instances. Mostly I pass an index as parameter to the class instance, or I use a public var to set the index. Using this way it is very easy to create an automatically filled index, since you have to set this up once and never worry again :)

Take a look at this code:

package
{
  public class MyObject
  {
    public static var global_index:int = 0;
    public const INDEX:int = global_index++;

     // constructor
     public function MyObject():void {}
  }
}
 

As you see, I have created a static variable global_index, which is always the same to all MyObject classes. I also created a public constant ‘INDEX’, which would be unique in every instance. When the MyObject instance is created the index will be set to the global_index, and the global_index will increase by one. So that’s basically the trick to create the auto-increment index for your AS3 class.

Tagged with , , .

Multiple keys made easy with DictionaryQuick post here, a simple solution I found to have multiple keys enabled. Maybe most real game developers know better or more elegant solutions, but I found this useful enough to share it with you.

Here we go. Add these variable to your class. This is a Dictionary, which allows you to associate a value with an object key.

private var currentKeys:Dictionary = new Dictionary();
 

Then, in your constructor or wherever you assign eventListeners, add these (well-known) listeners, with the callback functions:

import flash.events.KeyboardEvent;

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);

private function onKeyDown(e:KeyboardEvent):void
{
    currentKeys[e.keyCode] = true;
}
       
private function onKeyUp(e:KeyboardEvent):void
{
    currentKeys[e.keyCode] = false;
}
 

Inside your enterframe-event or timer (were you want to detect which keys are pressed), you could these kind of detection.

import flash.ui.Keyboard;
import flash.events.Event;

private function onUpdate(e:Event):void
{
    if ( currentKeys[ Keyboard.SPACE ] )
    {
        tank.shoot();
    }
    if ( currentKeys[ Keyboard.RIGHT ] )
    {
        tank.targetDirection -= 0.1;
    }   
    if ( currentKeys[ Keyboard.LEFT ] )
    {
        tank.targetDirection += 0.1;
    }   
    if ( currentKeys[ Keyboard.UP ] )
    {
        tank.speed += tank.acceleration;
    }   
    if ( currentKeys[ Keyboard.DOWN ] )
    {
        tank.speed /= 1.8;
    }
}
 

I found that if you use some 3 or 4+ combinations of keys at the same time, the keyboard events are not triggered anymore, which is a bit of annoying bug in the FlashPlayer. I mean pressing forward and left and shooting at the same time could be a problem? Well; Hope this helps, I think its very easy and a great usage of the Dictionary.

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:

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 , , .

Quick post; How to crop the bitmap of your stage with AS3:

function crop( _x:Number, _y:Number, _width:Number, _height:Number, displayObject:DisplayObject = null):Bitmap
{
var cropArea:Rectangle = new Rectangle( 0, 0, _width, _height );
var croppedBitmap:Bitmap = new Bitmap( new BitmapData( _width, _height ), PixelSnapping.ALWAYS, true );
croppedBitmap.bitmapData.draw( (displayObject!=null) ? displayObject : stage, new Matrix(1, 0, 0, 1, -_x, -_y) , null, null, cropArea, true );
return croppedBitmap;
}
 

Usage:

var myCroppedImage:Bitmap = crop( 100, 100, 200, 200 );
this.addChild ( myCroppedImage );
 

To save the capture, use the ImageSaver class

Update: I’ve added a downloadable CropUtil class to googlecode.

Tagged with , .

Faster Math.abs() (4)

January 28th, 2009, under Actionscript, Code snippets.

Quick post :) This function returns the absolute value of a specified number. This is +/- 24x faster than the regular Math.abs().

public function abs( value:Number ):Number
{
return value < 0 ? -value : value;
}
 

Tagged with .