Archive for the ‘HOWTO’ Category

Tuesday, December 23rd, 2008

I have mentioned before that flash to unity3d communication is a key part of game development for the web now where you are using Unity3D as a higher end renderer and some of your other page elements might be flash. Now there is a new open source kit for this called u3dobject.

To get Flash and Unity3D to talk to one another in an HTML/XHTML page is pretty simple with javascript and with the internal Unity3D Application object and the ExternalInterface in Flash.  But there are lots of elements of that communication that can be consolidated and reused so you don’t have to recreate that over and over.  Various studios and programmers come up with their own kits but when it becomes a shared activity to get the best integration and make it more of a platform that is where things like swfobject, swfaddress and u3dobject come in.

So far swfobject is the standard for flash html embedding and unityObject is a similar take (but a bit dated) on that but now we have u3dObject that is open as well and a more official open source project for unity3D <–> flash integration and test harnesses for development when those two technologies are used together.

Unity3D <-> Flash Embedding Info:

Thursday, January 10th, 2008

Using SharedObjects in Flash is very simple. Flash has SharedObjects that have been in the player since Flash6 when the introduction of Flash Communication Server which is now Flash Media Server which is releasing version 3 soon (also remote SharedObjects in Red5 is an open source RTMP media server that is based on Flash Media Server). So we can thank this release for SharedObjects, Camera objects, Audio, lots of the NetConnections, protocol enhancements and many other things. However to keep the tips simple we will just touch on the local usage and post a series of posts on these objects.

SharedObjects locally and remote have changed the way offline is thought about and are the backbone of many offline systems and prototypes. They have been influential in moving storage locally to remote in a lightweight AMF0 or AMF3 format.

SharedObject is in the namespace in AS3.

Here we show how to use the local version of a SharedObject to store data in the most simple form.

var so:SharedObject = SharedObject.getLocal("userData"); "user1377"; "[hash] or pwd";
so.flush(); // writes changes to disk

You can see this is extremely simple to store data.Here we show how to use the local version of a SharedObject to retrieve data in the most simple form.

var so:SharedObject = SharedObject.getLocal("userData");
var username:String =;
var pwdhash:String =;

That is it! In the most basic form SharedObjects are more simple than cookies and also are quite nice living outside the bounds of the cookies folder. If a user deletes all cookies it will not delete the SharedObjects. To delete SharedObjects you need to roght click on the Flash player, go to Settings and delete the objects there.You can store any type of data Flash supports from objects to numbers to strings in the SharedObject data.

var so:SharedObject = SharedObject.getLocal("userData"); "user1377"; new Number(1337);
var obj:Object = new Object();
obj.prop = "value"; obj;
so.flush(); // writes changes to disk

For large applications SharedObjects local are great because users can have their SharedObject space set to a high amount of space or unlmited for large offline type apps or more complex apps stored in a state object. It gets interesting when you pass this to the server in AMF or extremely compact AMF3 format to a remote stored object, via remoting, Shared Object events or any way you want to.We will be posting more on remote shared objects and some of the other tools such as Camera and Streams for AS3 over the coming weeks and deeper into the Sync Events for remote and local SOs.Sephiroth has a great Python tool to peer into the SOs on disk.

The first version of SharedObject Reader was written in python 2.2.
This new version is written in C# (C Sharp) as it’s now part of FlashDevelop editor.

Red5 also does this as well as many AMF kits.

Sync Events for SharedObject (as they change they launch a sync event)

Event object type:
SyncEvent.type property =

Read more at adobe docs:

Sample from AS3 docs showing usage

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFieldType;

    public class SharedObjectExample extends Sprite {

        private var mySo:SharedObject;

        public function SharedObjectExample() {
            saveBtn.addEventListener(MouseEvent.CLICK, saveValue);
            clearBtn.addEventListener(MouseEvent.CLICK, clearValue);

            mySo = SharedObject.getLocal("application-name");
            output.appendText("SharedObject loaded...\n");
            output.appendText("loaded value: " + + "\n\n");

         private function saveValue(event:MouseEvent):void {
            output.appendText("saving value...\n");
   = input.text;

            var flushStatus:String = null;
            try {
                flushStatus = mySo.flush(10000);
            } catch (error:Error) {
                output.appendText("Error...Could not write SharedObject to disk\n");
            if (flushStatus != null) {
                switch (flushStatus) {
                    case SharedObjectFlushStatus.PENDING:
                        output.appendText("Requesting permission to save object...\n");
                        mySo.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
                    case SharedObjectFlushStatus.FLUSHED:
                        output.appendText("Value flushed to disk.\n");

        private function clearValue(event:MouseEvent):void {
            output.appendText("Cleared saved value...Reload SWF and the value should be \"undefined\".\n\n");

        private function onFlushStatus(event:NetStatusEvent):void {
            output.appendText("User closed permission dialog...\n");
            switch ( {
                case "SharedObject.Flush.Success":
                    output.appendText("User granted permission -- value saved.\n");
                case "SharedObject.Flush.Failed":
                    output.appendText("User denied permission -- value not saved.\n");

            mySo.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);

        // UI elements
        private var inputLbl:TextField;
        private var input:TextField;
        private var output:TextField;
        private var saveBtn:Sprite;
        private var clearBtn:Sprite;

        private function buildUI():void {
            // input label
            inputLbl = new TextField();
            inputLbl.x = 10;
            inputLbl.y = 10;
            inputLbl.text = "Value to save:";

            // input TextField
            input = new TextField();
            input.x = 80;
            input.y = 10;
            input.width = 100;
            input.height = 20;
            input.border = true;
            input.background = true;
            input.type = TextFieldType.INPUT;

            // output TextField
            output = new TextField();
            output.x = 10;
            output.y = 35;
            output.width = 250;
            output.height = 250;
            output.multiline = true;
            output.wordWrap = true;
            output.border = true;
            output.background = true;

            // Save button
            saveBtn = new Sprite();
            saveBtn.x = 190;
            saveBtn.y = 10;
            saveBtn.useHandCursor = true;
  , 0, 30, 20, 5, 5);
            var saveLbl:TextField = new TextField();
            saveLbl.text = "Save";
            saveLbl.selectable = false;

            // Clear button
            clearBtn = new Sprite();
            clearBtn.x = 230;
            clearBtn.y = 10;
            clearBtn.useHandCursor = true;
  , 0, 30, 20, 5, 5);
            var clearLbl:TextField = new TextField();
            clearLbl.text = "Clear";
            clearLbl.selectable = false;
Wednesday, October 17th, 2007

Currently working on some motion detection with flash/c# and webcams right now. Here’s a basic overview of some motion detection source files and tricks. Most motion detection is based on snapshots and finding brightness of a pixel with all combined colors, then comparing that to previous snapshots to detect enough variance and thus movement. If you have a webcam hooked up, this sample in Flash AS3 highlights this well showing the camera on the left, then the brightness snapshots on the right. It also has an indicator to the amount of movement due to much brightness.


Here is a nice example of motion detection using various motion detection algorithms in C#. This is built on the very slick AForge.NET Computer Imaging Library.

If you ever wanted your own motion detection or recording it is all possible with the basics of checking brightness and snapshots in the most simple form checking how much change or variance their was to bright pixels or the count of bright pixels compared to previous snapshots.

// Calculate white pixels

private int CalculateWhitePixels( Bitmap image )
    int count = 0;
    // lock difference image
    BitmapData data = image.LockBits( new Rectangle( 0, 0, width, height ),
        ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed );
    int offset = data.Stride - width;
        byte * ptr = (byte *) data.Scan0.ToPointer( );
        for ( int y = 0; y < height; y++ )
            for ( int x = 0; x < width; x++, ptr++ )
                count += ( (*ptr) >> 7 );
            ptr += offset;

    // unlock image
    image.UnlockBits( data );
    return count;

Flash AS2

In Flash this is also possible here is a good article from Flash8 that explains cycling through each pixel to compare the image data and implement motion detection from a webcam.

For instance the basics here show how you can compare each pixel and the change in the brightness for each pixel:


//color of the current pixel in the current snapshot

//red channel

//green channel

//blue channel

nl=Math.sqrt(nr*nr + ng*ng + nb*nb)

//color of the same pixel in the previous snapshot

//red channel

//green channel

//blue channel

bl=Math.sqrt(br*br + bg*bg + bb*bb);

//difference in brightness between now and before

//there was a change in this pixel

Flash AS3

Here is a link to grab a conversion of the AS2 Flash motion detection above to AS3.

Source of AS3 motion detection here.

Grant Skinner has done some interesting things with motion detection with Flash and webcams in the past in the incomplet gallery.

C# or other hardware accelerated capable kits are faster but AS3 and Flash with the new AVM2 virtual machine  should be about 10 times faster than AS2 as much of the improvement in performance and the virtual machine is on iteration speed increases such as loops (i.e. pixel loop).

Sunday, July 15th, 2007

Rafajafar posted a great tutorial on 3D Flash Perlin Noise dynamic terrain generations with AS3 and Sandy.

Sandy is a flash 3d engine that has been out just a little longer than Papervision3D. The code for Sandy is very clear and it is a great engine. I have experimented with it and found it to be a bit slower it seems that papervision but it has great tools, including an extra 3ds file importer in addition to the Collada and ASE formats that most flash 3d engines support.

Using Perlin Noise is very common in 3d engines to draw large terrains and realistic terrains for 3d games or simulations. This technique makes it very easy to make dynamic terrains or randomly generated terrains, water effects, fire, clouds, whatever your need.

The demo has terrain generation class that can be used to build the dynamic terrain generation and the perlin noise material movement.

Samples using the TerrainCreator class to make different terrains. This could be used to also make level editors and other components of the game making pipeline in flash 3d.

ter = new TerrainCreator("MyTerrain", 1000000,
128, 9, 6000, 6000, 10,60,60, false,false, 15,
BitmapDataChannel.BLUE, false);

//Gentle Hills
ter = new TerrainCreator("MyTerrain", 10, 128, 9,
6000, 6000, 10,120,120, false,false, 15, 7, true);

//Smooth Hills
ter = new TerrainCreator("MyTerrain", 10, 128, 9,
6000, 6000, 10,120,120, true,true, 30, 7, true);

ter = new TerrainCreator("MyTerrain", 30, 128, 3,
6000, 6000, 15,100,100, false,false, 10, 7, true);

Click here for the full tutorial and source files on 3D Flash Perlin Noise dynamic terrain generations with AS3 and Sandy.

Now if we could just fast forward 2-3 years on processor power and speed, or get hardware acceleration for Flash…

Tuesday, June 12th, 2007

Right clicking and other mouse support in flash is not really a shining star but in AS2/AS3 you *can* stuff the context menu with items. You can clear out all but Settings and About from the menu and stuff in other items that may pertain to a selected movieclip or the entire app you are building. This can be good when adding multiple functions into applications and for extra functions that you want to make available from a quick location such as full screen, selecting an item etc.

To enable a context menu for full screen capabilities take this example:

1) Make your document class of your AS3 Flash CS3 file to the class below.

import flash.display.*;
import flash.errors.*;
import flash.filters.*;
import flash.geom.*;
import flash.ui.*;
import flash.utils.*;
import flash.xml.*;
public class FullScreenTest extends MovieClip
public function FullScreenTest()
// create the context menu, remove the built-in items,
// and add our custom items
var fullscreenCM:ContextMenu = new ContextMenu();
fullscreenCM.addEventListener(ContextMenuEvent.MENU_SELECT, onContextMenuHandler);
var fs:ContextMenuItem = new ContextMenuItem("Show Full Screen" );
fs.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onShowFullScreen);
fullscreenCM.customItems.push( fs );
var xfs:ContextMenuItem = new ContextMenuItem("Exit Full Screen");
xfs.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onShowNormalScreen);
fullscreenCM.customItems.push( xfs );

// THAT IS SET TO A CLASS NAMED 'mc' that inherits from MovieClip
var m:MovieClip = new mc();
m.contextMenu = fullscreenCM;
// functions to enter and leave full screen mode
function onShowFullScreen(event:ContextMenuEvent):void
stage.displayState = StageDisplayState.FULL_SCREEN;
function onShowNormalScreen(event:ContextMenuEvent):void
stage.displayState = StageDisplayState.NORMAL;
// function to enable and disable the context menu items,
// based on what mode we are in.
function onContextMenuHandler(event:ContextMenuEvent):void
if (stage.displayState == StageDisplayState.NORMAL)
{[0].enabled = true; // show full screen button[1].enabled = false; // hide normal screen button
{[0].enabled = false; // hide full screen button[1].enabled = true; // shoe normal screen button

2) Now Export to HTML and be sure to change the exported parameters in the HTML file to allowFullScreen = true (for the fullscreen effect) and menu = true (for the ability to add in context menu items) to whatever library you use for embedding flash:

   'menu', 'true',
   'allowFullScreen', 'true'

OR if using HTML parameters

<param name="allowFullScreen" value="true" />
<param name="menu" value="true" />

You can view a sample here. (right click on the movie clip and ‘show full screen’, then ‘hide full screen’)

You can download a sample FlashCS3/AS3 version here.

If you want more information on fullscreen check here and here (downloadable sample and component).

Wednesday, May 16th, 2007

Here is a small tutorial on scripting and its great changes in AS3 from AS2/AS1 thinking, we are focusing on mouse events currently.

The great thing about Flash9 and specifically AS3 (Actionscript3) is that it is starting to become a real programming platform and losing many of the silly hacks that is used to have. This is a good thing.

Old hacks like tellTarget are finally gone. Pixel level manipulation is possible and even faster. Real frameworks, excellent structured animation kits and even 3d engines are being built everyday. And invisible buttons are not needed anymore!

Like when people migrated from desktop to web, or VB6 to .NET, or OO to functional, we tend to try to reimplement the same solutions in new platforms even if there are better options because it worked before.

How to make movieclip buttons without invisible buttons via AS3 script…

Anything can be clickable and a button in AS3. Link a class to an object in a movie, dynamicly drawn asset or external asset and you are ready to make it a button.

Take for instance:

package draw.logic.tests
 import flash.display.*;

 public class GamePlayButton extends MovieClip
  public function GamePlayButton ()
   this.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
  function onMouseClickEvent(event:Event):void
    trace("mouse clicked on me");

You will note the addition of the event to the movie clip which makes it clickable.

this.addEventListener(MouseEvent.CLICK, onMouseClickEvent);

This again makes the movieclip clickable by listenting for the MouseEvent.CLICK event. This sample class can be linked to a movieclip for instance from the FLA library by going to Library > Properties then linking the class which would be draw.logic.tests.GamePlayButton in the above sample.

Great so we have a button now, on the MouseEvent.CLICK we are going to go to trace a message. All done right? Nope if you will notice the button does not get the linkable hand.

Make the Button Show the Mouse Cursor Hand

Well in old skool AS we might just slap an invisible button on there or make it a button type. Better yet let’s just set the this.buttonMode = true; in code which makes it a clickable button, listens to the click event, and get the hand to notify the user that it is a clickable item.

Sample script for a ‘play’ button

package draw.logic.tests
 import flash.display.*;

 public class GamePlayButton extends MovieClip
  public function GamePlayButton ()
   this.buttonMode = true;
   this.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
  function onMouseClickEvent(event:Event):void

Good Architecture and Design

In the past most items could be moved to .as files but you would have this mix of people that still put onEnterFrames or button click on(release) code in the FLA itself. AS3 I think finally makes it fully possible to remove code entirely from the FLA with only stop(); scripts for different frames.

A nice way to be is to have all script in external libraries and files removing all script from the FLA if possible. The script for buttons to the script for the main document class. The FLA is essentially just needed for library movieclips and AS3 real forces this separation. That combined with its general better structure makes this a much better platform than AS2 and Flash8, stop wasting your time developing in that and get to AS3 (take a gander at the better structured libraries in this migration link).

Best part of AS3 is the new clean event model, the basis on Javascript 2 spec and the clearer separation of code and assets for flash. More on the Mouse and Event model in AS3 and Timers, Loaders and more coming soon.

Sunday, May 13th, 2007

Mousewheel usage has been increasing now that almost everyone has a mouse with a wheel on it. Flash and specifically AS3 has capabilities to get lots of information about the mouse wheel movement and mouse movements in general.

In AS3 you wire up events like this:

stage.addEventListener(Event.RESIZE, onResizeEvent);

For mouse events you wire them up using the Mouse pseudo static enumeration MouseEvent:

stage.addEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheelEvent);

Inside of our flash class that we are wiring up events for we need to put the event function that we pass as an argument.

function onMouseWheelEvent(event:Event):void

As you can see the method passes the object in the event. Here we are getting the delta property of the object returned for the mousewheel event. You can get any of these properties that return (you can see this if you trace out the object).

 //[MouseEvent type="mouseWheel" bubbles=true cancelable=false eventPhase=2 localX=261 localY=241 stageX=261 stageY=241 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=-6]


The delta property is the amount and direction that the mouse wheel was moved up or down. If the delta is a positive integer then the mouse wheel was moved up, if negative it was moved down.

On my computer I have scrolling set to pages so it sets to 6 or -6 on all movements. Others that have different mouse customizations might only move 1 or 2 in either direction, mine moves six. This is important to note for game development or browsing with zoomable applications. Not all mousewheels are the same.

You can also see that there is a ctrlKey property and an altKey and shiftKey property to check if the user also has these down. This could be beneficial for navigation like in a 3d program or map where if you hold down shift or ctrl the application does different actions with the mouse wheel.

The mouse positions are also passed so you could check if what to scroll specifically or zoom. These mouse positional properties are available in other mouse events as well, you can always trace(event) to the passed event to see what it contains. You can also attach these events inside individual classes so that they only reacte to their own mouse wheel events rather than on the main stage.

SAMPLE MouseWheel script test file (make a new file and set this to the document class)

 import flash.display.*;
 import flash.ui.*;
  public class MouseWheelMain extends MovieClip
   public function MouseWheelMain()
    stage.addEventListener(MouseEvent.MOUSE_WHEEL,   onMouseWheelEvent);

    function onMouseWheelEvent(event:Event):void
     trace(; // amount mouse wheel moved
     // could do something like
     //movieToMove.x +=; // or any property like scaleX, scaleY, y, depth etc.

More on Mouse Events in AS3/Flash9/Flex here

Sunday, May 6th, 2007

We recently had a tutorial on making isometric assets for 3dsmax but this is the same tutorial for Maya. 

Orthographic cameras are again an isometric rendering that has no correct perspective, all edges are parallel, there is no vanishing point.  This is great for gaming or maps where you need the items at the bottom of the screen to be the same size as the items in the distance.

Many popular RTS or strategy games use this technique.  What it does is make it possible to create assets that can be exported and placed all over the game without the need to render at different distances.

Here’s the HOWTO to make Maya orthographic views for isometric gaming assets:

  1. Open your file in Maya (here is a great free one from You will usually be in persp or perspective view.  If not go to Panels > Perspective > persp.
    Photo Sharing and Video Hosting at Photobucket
  2. Create a new camera by going to Create > Cameras > Create Camera and Aim (this creates a target camera rather than a free camera)
  3. Position the camera (not the camera aim) by using the move tool on the camera to get it at a 45 degree angle at the corner). Then make sure the camera aim is at the base of the object (if you places it at 0,0,0 then it should be all set).
  4. Select the Camera.
  5. Now go to Panels > Cameras > View through Selected
  6. You are now viewing through the camera. Photo Sharing and Video Hosting at Photobucket
  7. Usually you have to adjust it a bit here so get it so that the camera is pointed at the corner of the building with the move tools on the selected camera.  Since this is a camera with aim you only have to move the camera and not worry about rotation and aim.  I have my aim set to the bottom of the building.
  8. After you get the view right (you can manually set the angle at 45 degrees up and to the side or aim it manually) jump into the camera by selecting it with the list, Photo Sharing and Video Hosting at Photobucket then clicking Panels > View though Selected.
  9. To make it orthographic in the properties select the Orthographic panel, then check “Orthographic”.
    Photo Sharing and Video Hosting at Photobucket
  10. At this point it will proabably zoom in so you need to move the view by zooming in our out to make it fit. 
    Photo Sharing and Video Hosting at Photobucket
  11. Now your model is in orthographic or isometric view so you can export it out to your game. 
    Photo Sharing and Video Hosting at Photobucket
  12. The ideal solution is to create a maya scene and import all your buildings, cars, or other game assets in individually and then export them individually with the same light and direction/angle so you can piece it together in the game and take advantage of reuse and loading only areas being shown.Photo Sharing and Video Hosting at Photobucket
Saturday, April 21st, 2007

{ draw logic } will be presenting HOWTOs every once in a while based on current projects or very simple, targeted actions in game development, programming, data design etc. 

Setup an Orthographic Camera in 3dsMax9

Axonometric Projection allows you to make flat Isometric game assets or views sometimes needed for maps layouts where false or flat 3D is used so you can see the items up close as well as you can see the items off in the distance. This view was common in the early sim citygames and many RPGs like Command and Conquer Red Alert (oh no not the blimps!). Photo Sharing and Video Hosting at Photobucket

Orthographic views are a camera setting that makes it so there is no vanishing point or correct perspective but instead parallel external lines. Sometimes this is key in scrolling 2d games or maps like I said but its also to help reuse assets over and over to create a better cache to pull from.  Orthographic viewscan also make flattening textures to be used in texturing in isometric games very simple.

To setup a camera in 3d Studio Max for orthographic renders follow these steps:

  1. Open up your file and get a perspective you want. Usually this is a diagonal 45 degree view or a 45 degree angle where 2/3 of one side shows and 1/3 of the other showsPhoto Sharing and Video Hosting at Photobucket
  2. Go to the perspective view and click in it. 
  3. Create a new camera by clicking CTRL+C. This will create a new ‘Camera01‘.
  4. Click C to jump into your new camera.
    Photo Sharing and Video Hosting at Photobucket
  5. As you can see this view has the perspective vanishing point and the lines on the outside of the model will eventually meet on the horizon.  For game assets this doesn’t always work when making an isometric or axonometric view.We want to make it an orthographic view so that there is a void of perspective and correct vanishing lines.
  6. To flatten this true perspective make sure the camera is still selected by clicking on the camera or by pressing ‘C’ (brings up all cameras as ‘P’ does the perspective view again) or selecting it from the object list.
  7.  Then under the modifiers tabs check the “Orthographic Projection” checkmark.Photo Sharing and Video Hosting at Photobucket 
  8. All done, now make a boatload more assets for your game/project!

See the difference in renders here:

True Perspective View:
Photo Sharing and Video Hosting at Photobucket

Orthographic View:
Photo Sharing and Video Hosting at Photobucket 

You can see that if the homes were to be stacked in rows where their walls are parallel (like the command and conquer screenshot above) the orthographic view is more suited for games or maps where you need to see all items the same size or scale. Click here to see a flash version of this that stretched full screen fluid flash.

Photo Sharing and Video Hosting at Photobucket

Here’s the MAX file source of the house. I used 3dsmax9 and built on a model I found online making it more cartoonish and simplistic/vector-like. For this tutorial some of the settings may be changed in your version but all 3d programs have this setting somewhere even if you are not using 3dsmax.