Gaming Your Way

May contain nuts.

Idiot's guid to skining GUI in Unity.

As I already mentioned, the Unity docs are not quite what I would call helpfull. I think they cover a lot and most of it will solve your problem, finding the right info in them is what really is the hard part.

Take the GUI scripting guide for instance "Reference Manual > GUI Scripting Guide", this covers everything you need to know to build a GUI. My mission currently is to create a simple form for the game I talked about earlier.
For the salutation I needed a drop down list, so I had to do it on my own, because that's the one usefull control I missed.


unity_igts_00.png
After a few hours I came up with this (scaled down a bit)


The form is dynamic (you can turn of the salutation for instance) and already has a working validation, but it's dead ugly. So the next task was to skin that up ("Reference Manual > GUI Scripting Guide > Customization").

Yet again the manual does a good job to tell you what you can do, but fucking lacks some basic examples on how to deal with the textures to skin up buttons for instance. That's where I got a bit pissy (although I must admit that I hate searching in boards or wikis when the solution should be in the manuals).

So the key to skinning the buttons (and the rest of the UI elements is the GUISkin file or for single use the GUIStyle. I knew that there has been a psd file with "templates" of the default textures used, but alas I still havent been able to find it again, though I know I saw it while playing with Unity for the first day (and I was like wtf?).

unity_igts_01.png
After skinning for a few minutes


I found the most valuable (and yet again MISSED info) in the scripting guide (after just testing it with a basic psd file) ...
So I looked at the default values of a new Skin and saw this:

unity_igts_02.png And I wondered why (and how) it'll become this: unity_igts_03.png.

What the manual is missing badly is the info that you can set a "fixed" border for a texture in a skin that isn't stretched:

var border : RectOffset
Description

The borders of all background images.

This corresponds to the border settings for GUITextures. It only affects the rendering of the background image and has no effect on positioning.

Why do I need to find that out by testing? (I guess no one reads through the scripting guide until he needs a specific info, I for sure do not)

By default the border values are set to:
left: 6, right: 6, top: 6, bottom: 4 ...

After knowing this it was oh so easy to just do this: unity_igts_04.png to get to the buttons used above.

Oh well.

I hope that saves some ugly searching for you,
nGFX

From script to code and back - just to discover coding again

Hi folks,

most regular readers will have noticed that we've jumped onto the Unity wagon after it finally came out for the windows world and so I think it's time to write down a few of my thoughts ...

What it is:
an easy to use development platform for 3d games (although easy, well, I'll cover that later)

What it is not:
Simply put: easy.
And it is not flash.

So?
The best part of it is, that you can do a decent 3d based game with it quite quickly, that is if you know how to code unity (I might have twittered once or twice that the docs are not one of the strong points) and (what's more important if you or someone in your team) can do low poly 3d.

So?
I really can't stress enough that it is NOT flash, not at all, when you get started with Unity all is nice and straight forward, but once you hit the point where you really would like to do a quick tween for the main menu, or use a fancy drop shadow on your font ... you'll probably start cursing and wish you could use a timeline and some keyframes.

One of the really big letdowns for me was to discover that a quick, easy and nice UI is not going to happen fast in Unity. You can get away with it if you don't need dynamic text to appear, but I need to do a lot of stuff with that, because nearly all of our games are prepared to be played in at least two languages.

How does all that relate to the title?
When I first got in touch with flash (6 I think) AS was really nothing more than a scripting language, coding for the best part was ... shit and most of us messed with onEnterFrames per movielclip. Then AS2 hit the light of the day and with AS3 it came very close to real coding ...
But when I entered the Unity world it seems like the old distributed scripts came back to haunt me. You've got the choice of using a set of different languages: javascript like, c#, boo and some others.

JS on the one hand is easy to use, ridiculously lose typed and commonly used. I really don't like lose typed coding, so for me it was c# ...
Anyway something that commes very close the the old MC based onEnterFrame is Update ... so a script that would move the object 1 "unit" (since we have no pixel) to the left would be:

function Update () {
    transform.position.x++;
}

(or something very close to that, I said I use c#, oh and I'm sure I saw some other methods to do the same)

Save that as a ".js" text file, add that to a cube on stage and viola (there you have the back to script part covered).

I hope you won't be doing that for a complex game, but ... thinking back ... I knew people who did that with flash  ** shudder **.

As I already mentioned, I hate lose typed coding and as I used c# for some years now for coding anyway it was a logical choice (that and the fact that I could continue using Visual Studio).

Oh and did I stress that there is NO timeline?

Everything you want to have animated either needs to be coded (ie for dynamic text) or already be animated in a 3d app ...

Oops, I think I need to get back to work ...

nGFX

ps: just to have something to look at a screenie of the menu (the start of a camera move) of my "test" game to see how I get along with Unity, if everything works well, I might be able to invite for a private beta test on Friday (give me a shout if you want to) ...

pots_menu_de_00.jpg
(the text for the menu was a big lesson in cheating, it uses GUI.Button, btw)

 

Self reflection ....

Hi all.

Back on coding CE again (at least for a few hours today) after spending a good deal of time coding and designing the backend for MYW, writing a tiny versatile CMS and doing some 3d for X.

So today I'm  going to ask myself why the hell I have done a few things in CE the way I did them (I bet you are a lot wiser now).

Let's raise the question if it is worth to add the extra amount of work needed to draw a hard line between the game's "engine" and the game's UI - for your average flash game.

You may have noticed that neither Squize nor me tend to make out lives overly easy when it comes to games, for some odd reason we both tend to try to give out very best for each and every game (even if it is a pain in the back) - well call that stupid.

Give me a good reason to split game and game (play) UI ...
The best reason I can come up with is: reusability, and it is also the least used one.

In most cases I can come up with there seems to be no reason to really split things, because the game is a one-of-a-kind thing. Even for games that share a good deal of similarites (like Wintertales and LogiMotion), a whole lot of things need to be rewritten in order to reuse the engine.

That leaves the reusability inside a single game. !?

WTH?

Inside a single game? Yep!

A good deal of our games either uses an ingame editor (although not usable by the player)  or uses an external editor to generate the level data. Mostly, but not always they share the same visuals. For instance the editor for Logimotion uses smaller tiles than the game itself (so have room for the tools and don't have to scroll the map). That is a good reason to split things between the UI and the "engine".
Another good reason is when you have a stupid designer and you just code - you know those guys tend to be smart and change the size of the assets as often as you should change your underwear.

So why question that and not do it all the time?

Well, it takes a good deal more planing to really split things up. in an ideal world, the "game" knows nothing about the UI, but it still has to control it (ie. update the score, display infos). In my case this is done using callbacks.
A good example might be a game we did (but still isn't playable online): CC


cc_game_00.jpg
(CC game, using 40x40 tiles)

 

cc_editor_00.jpg
(CC editor, using 32x32 tiles)


As you're meant to be able to play the game inside the editor (without leaving it), the engine had to cope with different tile sizes and environments.

So whenever the game needs to comunicate with its surroundings I provide a callback method, if I would have made it "the right" way, I should have used an interface for that, but ... hell you can overdo it too.

To make it easier and not having an endless number of callback methds I used only a few and gave them params (which are stored in the game's class as constants: like:

public static const UPDATEUI_INFO:uint = 0;
public static const UPDATEUI_BTNPLAY:uint = 1;
public static const UPDATEUI_ITEM:uint = 2;
public static const UPDATEUI_WIN:uint = 3;

Whenever you finish a level, the game would just call the callback provided for UI updates and pass the parameter needed.

And is it really worth the extra work?
Not always.

I like to spend that extra piece of work for games that require and editor or might have parts in it that seem to be a good start for reusing it in a second game. Sometimes you notice halfway through the project that you need to change something to make the game work again (ie. different tile size, or different UI), sometimes (like I did for CE) you notice that the game will be a one of and you cause yourself a good deal of fuzz for "nice code" only.

Well, lets get back coding CE.

nGFX


Everyone's loving those 4096 bytes

The 4K comp is gathering pace which is great ( Actually finished my game last night / this morning. I had some ideas the other night on how to improve it and it was quite nasty going from being "well" under the limit at around 4070 bytes and then going over with the new code. I was on 4099 bytes for quite a while last night until I cracked it. 4093 bytes and done, which is cool. I was going to be a clever sod and round that up to 4096 exactly, then realised that someone will do something in 2.5k that'll crap on my game and I'll just look silly for having used the max available and making something which isn't as good )

Rich over at photonStorm has posted some great tips for those of you giving the comp a bash in as3.

I opted for F8 / as2, although it's written like as1 with datatyping ( No Delegate or classes here ). Publishing as F7 would have saved a few bytes, but I wanted some of the filter effects.
I'm not sure what I can pass on that may be some use, but here goes ( Remember it applies to F8 / as2, the rules could be totally different for say F5 / as1, the size report is your friend with this comp ).

Chaining vars is actually longer, eg

score=level=d=cnt=0;

is a bit bigger than

score=0;
level=0;
d=0;
cnt=0;

Loops seem shorter this way,

while(--i)

Although to be honest I didn't try for loops ( I always use while, just habit )

It's common knowledge that pre-as3 var names have an effect on  size and speed in terms of their length ( i is "better" then myTempLoopCounterVar ) but linkage names have an impact too, so "bb" is smaller than "baddieBullet". Common sense I know, but if you're not used to thinking it terms of making code as tight as possible it's easy to miss ( It was for me anyway ).

More general things I did was to re-use values as much as I could, for example when the player dies I have to move it out of the way so the collision checks don't get triggered again, so I set player._x=2000; because I use a setInterval afterwards to wait for the gameOver ( id=setInterval(gameOver,player._x); )

Another thing, which is so dirty, was to drop an enterFrame on to everything. Originally I did the usual looping through an array calling the objects mainloop, but by adding the code to the sprite itself you remove all the loop overhead and make each sprite self sufficient.

It's weird tearing up the rule book for this comp, it's like going back to as1 and doing all those nasty things we used to do just to get things working.
If you've not done anything yet I can really recommend giving it a bash. The deadline is ages away yet, it should only take you a couple of hours for a couple of evenings and it's really good fun, it gets you back in touch with coding again rather than just dropping huge bitmaps into your fla and using a tweening package.

Squize.

States machines in actionscript, nice and easy

December already, it really does fly.

I was chatting with our mate Jeff @ 8bitRocket the other week about function pointers / state machines and I thought it may be useful to quickly write something up about it here, as so much of my code relies on them and they do make life easier.

private var mainFunc:Function;

That's pretty much it.

I'm guessing all your routines have some sort of mainloop. Either you're old school and that's running on an enterFrame on each mc you're moving about or it's a public method in an object which you loop through and call every frame.

Let's take a space invaders mainloop as an example ( Psuedo-code ahead )

function mainloop():void{
  if(thisInvaderIsDeadFlag==true){
    return;
  }
  if(areWeDyingFlag==true){
    if(sprite.currentframe==endOfExplosionsFrame){
      thisInvaderIsDeadFlag=true;
    }
    return;
  }

  moveInvader();
  testForShootingAtPlayer();
  testForBeingHitByPlayersBullet();
}


That should hopefully be straight forward enough. In real life we wouldn't want to be testing for thisInvaderIsDeadFlag every time, we'd just remove this invader from our array of active ones, but this is just an example.

Now check this out,

mainFunc=mainloop_normal;

function mainloop():void{
    mainFunc();
}

function mainloop_normal():void{
    moveInvader();
    testForShootingAtPlayer();
    testForBeingHitByPlayersBullet();
}

Here we've set up our function pointer to point to mainloop_normal, and then we just call that one method in our mainloop() method. Cool so far ?

Now we're not checking to see if the invader is dead, or if it's exploding. That's good, because by default the vast majority of the time neither of those are going to be true, so it's a waste to check ( It's like waking up every morning and seeing if it's your birthday ).

At the moment it's more of a function pointer than a state machine as such, so next up is why doing it this way is so sexy...

function testForBeingHitByPlayersBullet():void{
    if(playerBullet.hitTest(thisInvaderSprite)){
       thisInvaderSprite.gotoAndPlay("firstExplodingFrame");
       mainFunc=mainloop_waitingToDie;
    }
}

Here's our testForBeingHitByPlayerBullet method from the main loop. Imagine that's just doing a hitTest, the invader to the player bullet. Bang, it's a collision, but instead of having to set our areWeDyingFlag from the original example, we just change the state machine.

function mainloop_waitingToDie():void{
  if(sprite.currentframe==endOfExplosionsFrame){
//Kill this invader totally, ie remove the mc
      mainFunc=null;
  }
}

In effect, no extra checks are needed every frame, we're only running what we need. We've got the advantage of a slight performance boost, but far more useful than that is the flexibility this gives us.

Say for example you want your invader to teleport in now, at the start instead of:

mainFunc=mainloop_normal;

we can now alter it to,

mainFunc=mainloop_waitingForInvaderToTeleportIn;

And run the code there waiting for your cool teleport effect to finish, and then just alter the mainFunc to carry on with our flow.

Running your code this way means you can chop and change states without having to have lots of extra conditionals in your code ( If the player is teleporting in, but that teleport tween isn't at frame 10 yet, then don't test for collisions with the player bullet etc. etc. ).

Any questions just hit that comment button,

Squize.

Jelly cube with an animated plasma texture

Quite a descriptive title for this post for a change.

651_jellyVectors.jpg

In this section of 651 we're running two effects, a bog standard RGB plasma effect and then a "Jelly vector" effect.

To create a plasma you're going to have to suck up to Math.sin, he's your daddy for this.

Firstly we pre-calc a colour table, eg.

        public function ColourTable(){
            colourTable=new Array();
            var cnt:Number=-1;
            var col:Number;
            var r:int;
            var g:int;
            var b:int;
            var offset:Number=3.1415;

//To avoid /4 for each pixel every frame, we just make the colour table 4 times as big
            while(++cnt!=256*4){
                r = 128 + 128 * Math.sin(offset * cnt / 32);
                g = 128 + 128 * Math.sin(offset * cnt / 64);
                b = 128 + 128 * Math.sin(offset * cnt / 128);
                col=(r << 16)+(g << 8)+b;
                colourTable.push(col);
                colourTable.push(col);
                colourTable.push(col);
                colourTable.push(col);
            }
        }

Here we're just creating what is in effect a gradient, so we have an array which smoothly goes from one colour to the last one. This will create an interesting effect, and if you're going for something colourful and eye-catching as a baddie in a platformer or a fun screensaver for a partypoker website, then it's ideal. When it comes to the look-up when we're plotting we'd need to divide the value by 4, so to avoid this we make the colour table 4 times larger than is really needed ( Often it's a balance between memory usage vs speed. An easy way to think of it is with loops. If your game didn't have any loops and you just copy / pasted the same thing over and over it would run quicker, but take a lot more memory, and be pretty insane ).

Right the colour table is done, next up we create instances of our Pixel class,

            activePixelsStorage=new Array();
            var pixelObj:Pixels;
            var j:int=-1;
            var k:int;
            while(++j!=120){
                k=-1;
                while(++k!=120){
                    pixelObj=new Pixels(new Point(j,k),colourTable);
                    activePixelsStorage.push(pixelObj);
                }
            }    

It's just like doing a tile based engine, each instance of our Pixel class is passed an x/y position so our plasma is 120 pixels wide by 120 high. That's pretty tiny so we double the scale of the sprite in which we're plotting and add a blur filter just to smooth it out. It's a lot less expensive than plotting a 240x240 plasma.

On to the actual Pixel class:

    public class Pixels{
//---------------------------------------------------------------------------------------
// Properties
//---------------------------------------------------------------------------------------
        private var xPos:int;
        private var yPos:int;

        private var cX:Number;
        private var cY:Number;
        
        private var jointDist:Number;
        
        private var offset:int;

        private var cT:Array;
        
//---------------------------------------------------------------------------------------
//Constructor
//---------------------------------------------------------------------------------------
        public function Pixels(pos:Point,colourTableArg:Array):void{
            cX=xPos=pos.x;
            cY=yPos=pos.y;
            var xDist:int=120-cX;            //Distance from the bottom
            var yDist:int=120-cY;

            cT=colourTableArg;
            
            var distance:Number=Math.round((Math.sqrt((xDist*xDist)+(yDist*yDist))/2));
            var distX:Number=256 * Math.sin(distance/8);
            var distY:Number=256 * Math.cos(distance/8);

            jointDist=distX+distY;
       }
        
//---------------------------------------------------------------------------------------
//Public
//---------------------------------------------------------------------------------------
        public function toString():String {
            return "Pixels";
        }        

//---------------------------------------------------------------------------------------
        public function pixelmainloop(x:Number,y:Number,plotbm:BitmapData):void{
            offset = (Math.cos((xPos+x)*0.0525) + Math.sin((yPos+y)*0.0255))*256 + jointDist;

            if(offset<0){
                offset=(offset ^ -1) + 1;
            }
            
            plotbm.setPixel(xPos,yPos,cT[offset]);
        }
    }

I'm not going to go into too much detail with this, as it'll take ages to be honest. The most interesting part is the pixelmainloop, where we pass in the x/y ( As well as the bitmapData we're plotting too, more on that soon ), and from those coords we create an offset into the colour table. To create the smooth curves that makes a plasma look so sexy we use some lovely sin and cos ( That's the bit I'm skipping explaining in any real detail. It takes quite a bit of tweaking to get something looking how you like and different values really give different results, for example:

            offset = (Math.cos((xPos+x)*0.0525) + Math.sin((yPos+y)*0.0255))*64 + jointDist;
            offset=offset>>3;

That's what's used in the credits plasma / kaleidoscope effect, which uses exactly the same colour table values but looks totally different ).

All that's left for the plasma part is the mainloop that we run on the enterFrame.

            sinOffset++;
            var radian:Number = sinOffset/60;
            paletteShiftX = 128-Math.sin(radian)*255;
            paletteShiftY = 128-Math.cos(radian)*255;

            plotbm.lock();

            var pixelObj:Pixels;
            for each(pixelObj in activePixelsStorage){
                pixelObj.pixelmainloop(paletteShiftX,paletteShiftY,plotbm);
            }

            plotbm.unlock();

            if(plotbm==bm1){
                plotbm=bm2;
            } else {
                plotbm=bm1;
            }

            bmData1.bitmapData=plotbm;

Nothing too tricky here. We just increase the position ( Offset ) into the colour table every frame, and then use for...each ( Much quicker ) to loop through all our Pixel instances calling the pixelmainloop and passing the args.
The part that may be of interest is the plotbm var. To increase speed slightly we double buffer the plasma bitmap, so when one bitmapData is being displayed we're plotting to the other one which is no longer being shown.
To try and explain that a little better, we have two bitmapData objects, bm1 and bm2. bmData1 is our bitmap ( I find the difference between the two confusing as hell in as3. It makes total sense, it just doesn't seem to stay in my brain very well ) which is attached to the our holder sprite for the plasma ( The one we doubled in size and added a blur to as mentioned earlier ).
So lets say we have something like this:
holderSprite.bmData1.bm1;
And that's what you see on screen. If you can see bm1 that means we're plotting to bm2, and visa versa.

This is why we pass the currently hidden bitmapData to each instance of the Pixel class every frame rather than just passing one value in during it's construction.

That's plasmas for you. I've only really given the core concept as hopefully a spring board for your own experiments.

The Jelly cube is going to be much more straight forward, because someone else wrote the clever bit. After x amount of time we run a really quick white up over the whole stage, and that's where we remove the plasma all together and replace it with a papervision cube.

Ultra simple, we just rotate him and scale him. The twister code came from the excellent zupko who kindly open sourced it. Now we've got a twisty cube, what about the texture ?

This is another big fat cheat. At best you can get a plasma running the size we have at around 40fps, so there's no way we could do it realtime and run the cube. One idea I had early on was to use draw() on every frame of the plasma and store those away, then update the texture every frame on the cube using those stored away bitmaps.
I didn't go this route as I was concerned about the amount of memory it would use and I was concerned that using draw() may have had a negative performance hit when actually running the plasma ( I'm possibly paranoid about that and it would more than likely be fine, but it felt like quite a bit of data to be copying every frame when you want everything running as quickly as possible ).

The solution ? flv baby. Unless it's youTube the flv format seems to be badly over looked when it can be used for all types of tricks ( I did quite a bit of video work in games at preloaded long before flv came out so I've learnt what the advantages of using video are early on ).
I just ran the plasma for a little while grabbing the frames, cropped them up, created a copy running backwards and then joined the two together, so runs as A > B > A.
All that was left then was to created a flv texture for each side of the cube, and papervision along with Flash did everything for me.

The only thing left to cover off is the black outline on the cube. Again ultra simple, it's just a glow filter. Set it to black, turn up the strength, turn down the blurring and you've got a sexy outline.

Phew. I think this is going to be last in-depth-ish tut on the 651 effects. Not only does it takes ages, but I think the rest of the effects not touched on so far can be summarised in one post.

Squize.


Bitwise AND, IF and a big WTF

So what's wrong with this code:

if (this._iDrawLayer & ChipsGame.VIEW_LAYER_A == ChipsGame.VIEW_LAYER_A) {
// draw contents of layer A ...
}

nothing, really. Nonetheless it's not working in CS3 (yet again, prove me wrong).

Basically it's just the unoptimized check if a certain bit is set or not. Let's do some traces:

trace ("with ():", ((this._iDrawLayer & ChipsGame.VIEW_LAYER_A) == ChipsGame.VIEW_LAYER_A))
trace ("without ():", (this._iDrawLayer & ChipsGame.VIEW_LAYER_A == ChipsGame.VIEW_LAYER_A))
trace ("values :", this._iDrawLayer & ChipsGame.VIEW_LAYER_A , ChipsGame.VIEW_LAYER_A)

The result is this:

with (): true
without (): 1
values: 1 1

Interesting, isn't it?
It seems like the compiler chains the & and the == for some reason that escapes me...

So if you get something undesiered with bitwise operators ... use ( and ) around it.

nGFX

The sound of silience ...

Back again!

After a good deal of time I finally have something to post about - or let's face it moan about.

As the headling slightly might suggest I'm dealing with sound today.
I think that sound handling in AS3 is a nightmare compared to the ease of it in AS1/2 and I'm not the only one asking WTF?

So in order to play your sound you have to instanciate it, if it's exported CS3 kindly creates a class for you so you can easily use it ... (loading it from an external source is another story)

This is what the CS3 help gives us for embeded sounds ("working with embeded sounds"):

var drum:DrumSound = new DrumSound();
var channel:SoundChannel = drum.play();

My first question was: what do I need the SoundChannel for if I just want to play the sound?

Well, the rocket scientists at Adobe thought that it would be a good idea to add a play() command to the Sound, but not a stop(), so in order to stop our sound playing we *need* the SoundChannel - so we better store it for later use.

Anyway, to make my life easier I converted my SoundUtil class from AS2, basically it deals with the sounds so I don't have to think about it, it has a few usefull commands like playSFX (plays a sound effect, once), playMusic (which allows fading), crossfade ...
I usually used attached sounds (or from an external swf, but the SoundUtil dealt with it ...)
So in order to play music for the menu I'd just do:

SoundUtil.getInstance().playMusic("musicName", 2); // 2 would do a 2 sec. fade in

The AS3 version should work the same, although it uses static functions which then call the singleton's method.

Oh wait. We need to have a class to start the embeded sound ...

To get over that I wrote the add method, which basically takes the name of the sound (or the classname) and then does it's magic.

        public function add (strSound:String, bIsMusic:Boolean):void {
            
            var refClass:Class = getDefinitionByName(strSound) as Class;
            var sndTmp:Sound = new refClass();
                        
            var iTmp:int = this._aSound.length;
            
            this._aSound.push(sndTmp);
            this._objSound[strSound] = { id:iTmp, bIsMusic: bIsMusic };
            
            if (bIsMusic) {
                this._objSound[strSound].spDummy = new Sprite();
            }
            
        }

Ha! that was easy ...

As you see the sounds name gets stored in an object (I just use it as dictionairy), I store an Object with some more values along with the name. And you surely might ask WHY on earth I did create a Sprite for music files ...
Well I'm a lamer, I use the Sprite to attach an onEnterFrameTo it for things like fading :)

Fast forward ...

k. Let's say we play some music, and only wont it to play 2 times, after that the sound should be removed from memory. Luckily we have the onSoundComplete Event, it should return (CS3 help): "The Sound object on which a sound has finished playing."

For me it reads like it returns the Sound that is playing. FAIL!

It does however return a SoundChannel, which of course HAS no information (prove me wrong) about the Sound it belongs to ...
So how can I unload/cleanup a Sound when an onSoundComplete occurs, if I don't know which Sound is playing (and don't want to write a seperate Listner for each sound)?

Oh lucky me...

Thank fuck I store a lot of things in my information object (not only what is shown in the add method), for instance I store the SoundChannel I got from Sound's play() command and I store if a Sound is playing ...

After a few hours of using our favorite search engine I came up with something so stupid it might even be brilliant ...

private function onSoundComplete (e:Event):void {
            
      var strKey:String;
            
      for (strKey in this._objSound) {
           if (this._objSound[strKey].bIsMusic) {
               if (this._objSound[strKey].chChannel == e.target) {
                   this._objSound[strKey].chChannel.removeEventListener(Event.SOUND_COMPLETE, this.onSoundComplete);
                   this._objSound[strKey].bIsPlaying = false;
                   // do some cleanup
               }
           }
       }
            
}

Basically I loop over all music "files" that are playing and *compare* their SoundChannel with the one returned by the Event.
That's so insanely stupid! But it works. Sweet.

Maybe it helps some of you ...

nGFX

Infinite bobs

Here's another really old trick we used in 651.

651_bobs.jpg

Way back in Amigaland software sprites ( ie, sprites which were plotted by the blitter as opposed to being hardware based, like a mouse pointer ) were called "Bobs" ( Blitter OBjects ). As with everything you could only ever run a certain amount before you started running out of cpu time, so when the first infinite bob effects started appearing in demos every one passed a little bit of involuntary wee.

//------------------------------------------------
// Bob properties
//------------------------------------------------
        private var ball:Sprite;
        
        private var bm1:BitmapData;
        private var bm2:BitmapData;
        private var bm3:BitmapData;
        private var bmData1:Bitmap;
        private var bmData2:Bitmap;
        private var bmData3:Bitmap;

        private var currentBitmapNumber:int;

Just set up 3 bitmaps, and then...

//Set up the sprites
            container=new Sprite();
            stage.addChild(container);
            
            playField=new Sprite();
            container.addChild(playField);

Create a holder sprite + add it to the stage, and then a further sprite within that. Also add your bob to the playField ( Not the container or the stage )

Next up, our mainloop,

//---------------------------------------------------------------------------------------
        private function mainloop(e:Event):void{
            moveBob();
            copyBitmap();
}

moveBob() is however you want to move the bob around the screen, use your nice sin based movement that you've got tucked away. All it's doing is just moving one bob ( ball:Sprite in this case ) around the screen.

The funky bit is the copyBitmap() method,

 

//---------------------------------------------------------------------------------------
        private function copyBitmap():void{
            container.addChild(this["bmData"+currentBitmapNumber]);
            this["bm"+currentBitmapNumber].draw(playField);

            if(++currentBitmapNumber==4){
                currentBitmapNumber=1;
            }
        }

It just simply loops through all our bitmaps, copying what's in our playField ( ie the ball ) to the next bitmap. Just written down like this it's a bit tricky to grasp, think of it like an old flick book. You move the bob, you take a copy of the whole screen and store that in a bitmap and then display that, you then move the bob again, and take another grab of it and so on. We use 3 bitmaps because the image will be slightly different on all of them, creating the sense of movement ( Otherwise it wouldn't animate and would just look like a trail behind the bob ).

I can recommend giving it a quick play, it'll take 5 mins to set yourself up with a working example and once it's running infront of you it'll click into place how it actually does work.

Squize.

 

How it does what it does.

Now 651 is history I thought it may be of interest to go through how some of the parts work.

Let's start with the boring bit for today, the actual structure. To make testing it easier, and to be able to swap and change the order to make sure it felt right, I used a pretty simple yet modular approach,

//------------------------------------------------
// Demo classes
//------------------------------------------------
        private var logo:Logo;
        private var credits:Credits;
        private var twister:Twister;
        private var vectorBalls:VectorBalls;
        private var pimp:Pimp;
        private var showReel:ShowReel;
        private var water:Water;
        private var fin:Fin;
        
        private var sequenceOrder:Array=new Array("logo","twister","vectorBalls","pimp","credits","showReel","water","fin");
        private var sequenceOffset:int;


The sequenceOrder array kinda speaks for itself. The other part of the code is just as straight forward:

//---------------------------------------------------------------------------------------
        public function sequence():void{
            switch (sequenceOrder[sequenceOffset]){
                case "logo":
                    logo=new Logo();
                    break;    
                case "twister":
                    twister=new Twister();
                    break;    
                case "credits":
                    credits=new Credits();
                    break;    
                case "vectorBalls":
                    vectorBalls=new VectorBalls();
                    break;    
                case "pimp":
                    pimp=new Pimp();
                    break;    
                case "showReel":
                    showReel=new ShowReel();
                    break;    
                case "water":
                    water=new Water();
                    break;    
                case "fin":
                    fin=new Fin();
                    break;    
            }
        }

//---------------------------------------------------------------------------------------
        public function finished():void{
            if(++sequenceOffset==sequenceOrder.length){
//Finished            
            } else {
                sequence();
            }
        }


Each segment is totally independent, ie it has it's own init and housekeeping routines, there's no co-dependency at all. To start the demo the sequenceOffset var is set to 0 and then the sequence() method is called.
When a segment has finished, it calls it's houseKeeping() method to dispose of all the bitmaps and removes all the sprites from the stage, and then calls the finished() method ( Hence it being public ).

That's all there is to the underlying structure which runs the demo, it really doesn't get any more straight forward.

Squize.