Pagination is a navigation style where you have a bunch of content that won’t fit on one screen, so you give your user BACK and NEXT arrow keys to flip through “pages” displaying the content. In many ways, it’s preferable to a scrolling navigation, because you don’t have to fill the box with all of your content at once - you can pull it down for your user on demand. (note: i’ve seen a few rare cases where a the application downloads content as you scroll the list, but in my experience it’s not very common)

You see pagination everywhere, and i use it at least once in every single game i build. It’s just handy. Check out the puzzle gallery in Jigsaw! for an example:

Jigsaw Pagination

Pagination at work

When i was first learning Flash and i had to set up these paginated galleries all the time, i would constantly make the same mistake. The left arrow button would fire a function that would be almost identical to the right arrow button’s function. For some bizarre reason, it took me YEARS to figure out how to set this up without duplicating code.

If you’re a smartypants and you figured this out long ago, more power to you. But if you’re just learning and you have a similar problem, here’s the trick:

ID, please

The first thing you need is an ID to store which “page” the user is looking at. Remember that our gallery is going to be completely code-created, so there are no actual “pages” to speak of - you decide how many items will appear on your pages. But you’ll use this ID value to figure out which content to display.

//AS2:
var ID:Number;
 
//AS3:
var ID:uint;

That’s the variable declaration. When you initialize your gallery screen, set ID to 0.

mod

Next, i give each arrow button a variable called “mod“. That’s short for “modifier“. The LEFT/BACK/PREVIOUS arrow gets a mod of -1, while the RIGHT/FORWARD/NEXT button gets a mod of 1.

btnArrowLeftClip.mod = -1;
btnArrowRightClip.mod = 1;

Interactify it!

Set up some button events or event listeners for your arrow buttons, and pass each button’s mod value to a common function.

//AS2:
btnArrowLeftClip.onRelease =
            btnArrowRightClip.onRelease = function():Void
{
     flipGallery(this.mod);
}
 
//AS3:
btnArrowRightClip.mod = 1;
btnArrowLeftClip.mod = -1;
 
btnArrowLeftClip.addEventListener(MouseEvent.CLICK, flipGallery);
btnArrowRightClip.addEventListener(MouseEvent.CLICK, flipGallery);

Flip it real good

Now, you just set up a flipGallery function. It accepts mod (-1 or 1) as input and uses that to change the ID value.

// AS2:
flipGallery = function(mod:Number):Void
{
      ID += mod;  
      // If mod is -1, ID goes down.  If mod is 1, ID goes up.
}
 
//AS3:
function flipGallery(e:MouseEvent):void
{
      ID += e.target.mod;
}

That’s a Wrap (?)

You’ll want to add some logic to your flipGallery function to wrap the ID variable. Figure out how much stuff you have to display, then figure out how much stuff you can fit on one “page”. That will give you totalItems and totalItemsPerPage values. Do some division to calculate a totalPages value.

Then, within your flipGallery function/method:

if(ID >= totalPages) ID = 0;
if(ID < 0) ID = totalPages-1; 
      // we subtract 1 because we're working with 0-base counting

So what do you actually do with your flipGallery function once the ID is set properly? If you have all of the things you want to display numbered sequentially and linked from the library (or stored in an array), just loop through totalItemsPerPage. Multiply ID (current page) by totalItemsPerPage and add it to your iterative value (usually i in a for loop). That’s the number of the correct item to display … so display it!

There’s a little more work involved with actually laying out your items on the stage so that they’re not all lumped together. i’ll leave that up to your discretion. i just wanted to talk about the mod method, because i would have appreciated it very much if the Ghost of Christmas Future had written this article for me and emailed it to me back in 2002.

Ghost of Christmas Future helps Scrooge with Flash programming

Will Tiny Tim ever learn Actionscript, spirit?

Shall we have some more?

Was that helpful? Not? Do you have a way better way to do it? Is there another topic you want to see covered? Let me know!

- Ryan

PROBLEM:

Unloading content (ie external swfs) in AS3 is difficult, if not impossible.

SOLUTION:

My pal Martin Sieg at marblemedia threw me to an article by Grant Skinner - Failure to Unload: Flash Player 9’s Dirty Secret - where the author discusses a player bug that prevents content unloading. The problem impacts gallery-style projects, and sites that use embedded advertising.

Apparently there is no real solution, but Skinner is campaigning for a sandbox mode in Flash Player 10 where you can rope off your embedded content, and prevent it from getting its hooks into your main movie.

A noble effort, Grant. In other news, aid group World Vision announced today that rising food prices have created a shortfall that will prevent them from feeding millions of people.

AS3 and the Scoop on OOP

April 22nd, 2008

i was only trying to promote Flex Camp 2 when i launched into a long lament over Macromedia/Adobe’s chosen design path for their Flash software. Industry pal Jim McGinley (of TOJam 3 fame) shared his insights:

Visual Basic programmers had an inferiority complex. Despite the fact VB programmers were building business applications in record speed, VB programmers knew in their hearts they weren’t working with a ‘real’ programming language. Microsoft responded to this, and kept adding C++ features to the VB language, eventually releasing VB.Net. VB.Net is a REAL programming language with ALL of the features and capabilities found in C#. It takes twice as long to build business applications, and programmers love it!

Flash is following this classic pattern. Flex proves that Flash is becoming a real programming language. Eventually, Flash will wind up being C++ (Threads, OpenGL, ADO database layer), forgetting what made Flash great to begin with. Animations produced in the Flash design environment will be replaced by Actionscript code that does the same thing. It will take twice as long to build things in flash, and programmers will love it!

The Primordial Days of Flash

If you’re a college student who’s just been saddled with a Flash course, or you’re keen on creating a little interactive piece for your website, you may now be quaking in your boots at the prospect of wrapping your brain tentacles around Actionscript 3. It may surprise you to learn that Flash (née Futuresplash) was once a great little vector animation tool for artists. It developed a scripting language to help with starting and stopping animations, and supported the occasional button - a button to start and stop an animations, most likely.

i got into the game at Flash version 4, where all the scripts were in a tidy little box. You couldn’t actually type any code. You could only drag and drop the script you wanted into your scripting window, and fill in the blanks. For example, you could drag the playhead control script “gotoAndPlay();” to the scripting window, and fill in a frame number or a frame label to make it read “gotoAndPlay(”act4″);

i loved everything that Flash had to offer except its script controls. Although i never had any success all through my life with programming, i didn’t like coding in Flash 4. i could actually make a whole game by myself, which was great, but it felt like throwing pottery with boxing gloves on.

The upgrade to Flash 5 blew my mind, and marked the first step in my path toward the Dark Side. For the first time, i was able to type my own code. No training wheels, no boxing gloves - all i got was a big blank window. “The power,” i cackled - “the ABSOLUTE POWAHH!!!”

But with great power comes great responsibility (Luke said that long before Uncle Ben, by the bye), and with the freedom to type your own code came the burden of learning the Actionscript language and syntax inside and out - otherwise you’d get a famously cryptic compile-time error. To quote a certain colony of ants released into zero-gravity, “Freedom! Horrible freedom!”

New Designer Features Are Coming, Right?

With each version of Flash that the Macromedia team released, those of us from the design end of the gene pool (AKA the shallow end) anxiously awaited the newest art and animation features.

Would Flash be able to handle text along a path, like Illustrator and Photoshop?

What about curved gradients?

How about a swirl tool? Or the ability to freeform/perspective distort a movieclip?

What about inverse kinematics in Flash? Hell - what about forward kinematics?

Could you make it so that we can select a bunch of movieclips at the same time and swap them out all at once, instead of swapping every symbol instance one by one?

What about range-selecting a bunch of instances across your timeline and giving them all the same instance name with one click, instead of having to individually name all your instances in case you forgot to name that first instance before you went ahead and animated it across 300 frames?

How about time stretching? Can Flash time-stretch our animations in case we have to change the frame rate in the middle of a project?

Text Along a Path in Illustrator

Illustrator flagrantly mocks me.

No? So what do we designers get, then? Photoshop-style filters? Ok … alright. So after eight years of waiting, you’re giving us Photoshop-style filters like blur and drop shadow?

Hey uh … hey Adobe: 1997 called. THEY WANT THEIR CUTTING-EDGE DESIGN FEATURES BACK.

Toon Boom

Back when i was working at Corus Entertainment, a media conglomorate with several national stations boasting millions of viewers, i was trying to make a case for building the entire YTV.com site in Flash. We got pretty close, but the idea was eventually tossed when a new concept called “Search Engine Optimization” reminded everyone of Flash content’s depressing opacity. Still, i contacted Macromedia many times asking for support and advice, sharing site links with them to show off our department’s work and generally trying to bring on the love, but they weren’t having it.

Corus animation studio Nelvana seemed to have a similar problem. They animated a few different shows entirely in Flash, including Jacob Two-Two, which must have been a nightmare without any sort of linkage feature to sew characters’ limbs together. Plucky young upstart Toon Boom Studio listened to them and began building the features they requested, which included parallax background scrolling and a Maya-style hierarchy for all the kibbles n’ bits within a scene. Nelvana phased out Flash after a couple of years, and even bought Toon Boom to ensure that the software would continue to develop with animation production in mind.

In the end, the squeaky wheel gets the grease. And in the case of Flash, the nerds bemoaning improper coding practices won out; its scripting language was developed and refined until today’s Actionscript resembles many C-based languages out there. And aside from the occasional blur effect, the art and animation tools remain almost identical to the version i started using eight years ago in 2000.

Quick - Code this in Ten Minutes!

The fallout that i’m faced with is this: AS3 is not fast. Sure, it may be fast to the user, but that’s because the Flash virtual machine has offloaded the burden of figuring out a lot of junk onto the programmer. The result is that projects that i could quickly bang out in a week now take at least twice as long to build.

It’s not because i don’t know Actionscript 3 like i know Actionscript 2. i spent two months, eight hours a day, retraining myself to use AS3, and here’s my verdict: it’s simply slower. The fact that it forces an OOP (Object Oriented Programming) methodology on me means that instead of this:

var myWidget:Object = {};

i have to type this:

namespace ohGod.makeItStop.whattaPainInTheAss
{
import flash.whoCares.thisTakesTooLong.SomeNonsense;

public class Widget extends SomeNonsense
{
public function Widget()
{

}//constructor
}//class
}//namespace

//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*//

// Meanwhile, back at the ranch:
var myWidget:Widget = new Widget();

Count up those keystrokes. That’s a whole lot more typing.

Beyond that, there’s a whole lot more thinking and planning involved. You should no longer say this:

var myNum:Number;

… because the Flash Player wants to know what kind of number you need. Is it going to be signed or unsigned? With a decimal or no decimal? What’s the highest amount that number will ever reach?

You know what? Sometimes i have no idea. i don’t know, Flash. You tell me. i don’t want to have to go traipsing through additional manuals looking up the limits of your number datatypes because i don’t have time.

Many of the projects that we build at Untold Entertainment have a programming element of one to two weeks, max. It’s actually a competetive edge that we’re able to code so rapidly. So while OOP and strong-typing and proper class architecture are all nice things to have, so is a finished project.

Enemy Mine

Programmers just LOVE OOP because, theoretically, you can create modular, portable code that you can reuse in project after project. This is all true in the application world, where buttons all act in similar ways and windows all do the same nonsense from app to app. In fact, one could argue that applications are better when they adhere to a shared sense of design. i want to know in every app that when i click that the little underscore button on a window will minimize the window, instead of adjusting the application’s volume and installing a new graphics card driver for example.

Casual web games are a different story altogether. Some elements are handy to reuse - particularly a high score module, a timer, a Button class, a Sound Effects controller, and an on-screen Prompt or Dialogue routine. But OTHER elements, like the fire-breating fish who revolves around the central pivot point of the planet graphic shooting fireballs at a 37 degree angle and reacting to the player’s crossbow shots by randomly jumping or rolling - THAT kind of thing is a different story altogether.

Yes, you can build the fire-breathing fish using OOP methodology. You’d probably start really generally, maybe with a Character class. “Enemy” extends “Character” and inherits, maybe, a hitPoints member, and perhaps it has its own fire() and dodge() methods. That all sounds great - straight out of an OOP text book.

But then your next game has an evil squirrel enemy that walks orthogonally through an isometric environment, picking up any atomic acorns he finds and intermittently firing up a deadly force field.

Again, you can revisit your enemy class and tweak it so that your new enemy works, but those two Enemy cases are so different. There’s no way your original Enemy class is going to suit this new enemy character, because you simply can’t see into the future. You can’t foresee all your Enemy needs. And when “the future” is only two weeks away and you have to slam together the code for your current project, you’re not likely to futz around building the perfect reusable Enemy class all week.

Screw OOP

So screw OOP. Yeah - i said it. Object Oriented Programming is fine for organizing code, and certain things can be reused. But by and large, if you’re the type of user who doesn’t have a nine-month Flash project mapped out on a Gantt chart and hung on a wall so that you can interface with the twenty other people on the project and negotiate dependencies, then Adobe and Macromedia have totally screwed you - first by requiring you to adopt a methodology that’s only going to slow you down, and second by failing to deliver design features that actually would speed up production, such as those i mentioned earlier.

But hey - at least we’ve got blur. Perhaps in eight more years, the Adobe Flash gods will smile on us and give us lens flare.

Lens Flare

Toronto Flex Camp 2

April 15th, 2008

Flex Camp 2

That tattoo’s gonna look pretty silly when Adobe redesigns their Flex logo.

The TorontoFlex.org user group has announced its second Flex Camp:

Our second iteration of Flex Camp is coming on May 15, 2008 at the MaRS Centre (http://www.marsdd.com/Contact-MaRS.html).

This one promises to be even better than our premier event last fall. Along with Adobe’s Mike Potter, we’re privileged to have Ben Forta, the most well-known Adobe evangelist in the world. If you’ve never heard Ben speak before you’re in for a real treat!

Flex Camp, contrary to what you might think, is not a wilderness retreat for junior highschoolers where you go to experiment with homosexuality. No - it’s an event where you show up five minutes late and the promised meal has been completely devoured, and then at half-time when the organizers announce there are cookies in the next room and you charge out ahead of everyone because you missed dinner and have just sat through three hours of tech talk, only to find that a large group of attendees got bored and wandered into the cookie room hours earlier, decimating the cookie platters before the snack could even be announced.

Flex Camp is not so much a user group event, but a technologically-themed soup kitchen for Toronto’s college students.

The subject matter of the first Flex Camp flew right over my head, i’ll admit. It had something to do with using a programming paradigm called Loch Loman or Gormenghast or something to organize your code. Event organizer Oliver Merk spoke too abstractly for my liking, and it was especially difficult to concentrate with hunger gurgles gnawing away at my stomach lining.

Gormenghast

What this place has to do with web apps i’ll never know.

i appreciate that a user group should be able to focus on in-depth topics that go beyond a mere “introduction to Flex” idea, but i think the organizers went a touch too far. Flex is still so new that people seem to have a hard time understanding what it even is, let alone how to apply a programming paradigm to it.

If you’re a student looking for some free food, you’re bound to attend this event. In that case, the least you could do is to read up on Flex so that you can hold your own in a conversation while filling your pockets with little triangular egg salad sandwiches. Regard:

What the Heck is Flex?

Up until the release of Actionscript 3, people who programmed in Flash were not considered “real” programmers. Actionscript was derided by so-called “real” programmers as a “scripting language” rather than a programming language, which is like the difference between a community college and a university.

i always despised this viewpoint, because learning a programming language was very difficult for me, and i felt immensely satisfied that i was able to actually code things that functioned like honest-to-goodness real-live games and applications.

It wasn’t until i tried programming in C#, a “real” programming language, that i understood the comparison.

Mr. Fontsy Ponts

Flash is a tool that does a lot of stuff for you. You can just grab the Text tool, click on the screen and start typing. When you compile your movie, that text appears on the screen, in any outline you choose, and at any size in any colour you so desire.

If you’d like to do the same thing with C#, you have to make what’s called a font, or character, map:

Character Map

A character map. No bloody fun.

Then you have to train your program how to pick through and slice out a letter. So when you want to display the word “hello”, you tell your font rendering routine to go grab chunks of your character map at “h”, “e”, “l”, “l”, and “o”, and display those bitmaps on the screen.

That is, assuming you’ve programmed your game or app to display graphics on the screen. If not, you’ll have to code that or find a graphics renderer that someone else has coded.

It’s all part of what i like to call a Merry Pain in the Ass. But when so-called “real” programmers took a look at Flash, they said “What what what?? It draws the graphics for you?? But … but you lose so much control! And it could never render as quickly as something i wrote myself! And it’s … it’s not … hardcore enough!

Very well. So be it. You write your fast graphics engine while i bang out an entire game in a weekend.

Flex was created for these so-called “real” programmers to feel more at home. There are no drawing tools, no movieclips, and no shape tween drop-downs. In fact, there’s no actual program. Technically speaking, Flex is an Actionscript framework. The product name is used almost synonymously with “Flex Builder”, which is a plugin for a free programming IDE called Eclipse.

So you’re free to write in Flex, but if you want a tool to make it somewhat easier, you can buy Flex Builder for a few hundred bucks and extend the functionality of Eclipse. Flex has a few unique code libraries that Flash doesn’t have, and vice versa. You can’t create any graphics or animations with Flex or Flex Builder (except, technically, with the drawing API), so you still need some other creative authoring program like Flash, Photoshop, Fireworks, etc to create graphics, sounds, animations and movies.

Frex

Does that clear it up a little? i’m a very visual person myself, and i prefer having my graphics and animations right in front of me while i code. Although i am trying to warm up to FlashDevelop (more on that tool in another post), Flex isn’t really for me.

The thing that struck me most about the last Flex Camp, aside from wanting to gnaw my own leg off from sheer starvation, is that Flex coders are in high, high demand … possibly more than Flash people. Every presenter, every staffer and every attendee i spoke to was looking for a Flex coder. The drawback is that you usually have to build some kind of online accounting software or phramaceutical inventory system with it. But if that doesn’t bother you, give Flex - and Flex Camp 2 - a shot.

Just be sure to eat before you show up.

AS3 Tutorial - Math.random()

March 23rd, 2008

i haven’t written many Flash tutorials because i feel like a bit of a poser. i see the brilliant codeheads posting these tutes to make Flash do incredible things and i think “man - that’s leagues ahead of where i’m at.” But i forget that with eight years’ experience using Actionscript, i do actually know a thing or two that will help someone new to Flash/Actionscript.

This article is from an email i sent to a Humber College student explaining how to pull a random number in Flash, how to make it an integer, and how to get a random number within a range.

The student, Michael, was creating a game with an asteroid belt. He wanted to randomly distribute the asteroids along the y axis, and to give them a random speed value within a range. The range would increase with each new level.

~~ BEGIN TRANSMISSION ~~

Hi Michael.

Whenever you want x amount of something, that’s obviously your cue to create a variable. So since you need x amount of asteroids, let’s make a totalAsteroids variable:

var totalAsteroids:uint = 5;  // you can tweak this value up or down, of course

The other two things you’re looking at are random numbers within ranges. You need a random number within a range to distribute the asteroids along the y axis. You need a random number within a range to determine the speed of the asteroids, which goes up (i assume?) each level.

So! Here’s the basic random code:

var someNumber:Number = Math.random();

That’ll get you a decimal number betwen 0 and 1. Try running this code a few times in Flash to prove it:

var someNum:Number = Math.random();
trace(someNum);

You just multiply that number if you need a bigger range. Look at this:

var someNum:Number = Math.random()*5;

That will give you a decimal number between 0 and 5, because everything has been multiplied by 5.

Decimal numbers might not serve your purposes well. Here are a few ways to clean up your someNum result:

var someNum:Number = Math.floor(Math.random()*5);
// gives you 0, 1, 2, 3, or 4 by "flattening" the decimal number
var someNum:Number = Math.ceil(Math.random()*5);
// gives you 1, 2, 3, 4, or 5 by raising the decimal number
var someNum:Number = Math.round(Math.random()*5);
// gives you 0, 1, 2, 3, 4, or 5
by rounding the decimal number up or down

See? You just wrap Math.roundingMethod() around your Math.random() method. You stick your Math.random() statement inside the Math.roundingMethod() brackets.

So far so good. Now what if you need a random number within a range? Say, any number between 5 and 20?

Well, 20 minus 5 is 15. That’s your range. You need a random number out of 15.

Then just add the lower limit (5) to bump the number up. Does that make sense?

var someNum:Number = Math.ceil(Math.random()*15);
// gives you 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, or 15
var someNum:Number = Math.ceil(Math.random()*15) + 5;
// gives you 5, 6, 7, 8, ,9 ,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, or 20

So really, we could knock all these numbers out and just use variables.

var minLimit:uint = 5;
var maxLimit:uint = 20;
/* These two variables change
depending on the level of the game.
To be more specific, they'll probably
be called minSpeed and maxSpeed.*/
 
var range:uint = maxLimit - minLimit;
 
var someNum:Number = Math.ceil(Math.random()*range) + minLimit;

This works for your asteroid speed. It also works for asteroid placement. Do you see how? You’re just telling Flash the minimum limit for asteroid placement (somewhere near the top of the gameplay field) and the maxiumum limit (near the bottom of the screen). Then you pull a random number within that range and bump the number up by adding the minLimit value.

To create your asteroids field, loop through your totalAsteroids value, and for each asteroid you add to the screen from the library, get a random number within range and set the asteroid’s y position to that result.

for(var i:uint = 0; i<totalAsteroids; i++)
{
   var theAsteroid:Asteroid = new Asteroid();
   // create a new instance of your Asteroid class (not shown)
   var theClip:MovieClip = theAsteroid.clip = new AsteroidClip();
   // attach a MovieClip from the library
 
   theAsteroid.clip.y =
           Math.ceil(Math.random()*screenRange) + minYLimit;
   // Pull a random screen position
 
   theAsteroid.speed =
           Math.ceil(Math.random()*speedRange) + minSpeed;
   // Pull a random speed
 
   theAsteroid.dir = Math.round(Math.random())*2-1;
   // Randomly grab 1 or -1 for the direction.
   // During the game's update loop, multiply the speed
   // by the direction to make the asteroid move left to right,
   // or right to left
 
   theAsteroid.dir == 1 ?
           theAsteroid.clip.x = 0 : theAsteroid.clip.x = maxXLimit;
   // Put the asteroid at the right or left side of the screen,
   // depending on which direction it'll be travelling
 
   addChild(theAsteroid.clip);
   // Put that puppy on the stage!
}

Obviously what’s missing here is the game’s update and draw loops which will position the asteroids and position their graphics. i’ll save that for another post.

Addendum: Props to SmilyOrg from #actionscript on EFNet for the random direction code. i use it all the time, and i always forget how it goes.

PROBLEM:

MovieClip._xscale (or MovieClip.xscale) does not light up as a recognized property in AS3. It’s not even listed as a property of the MovieClip class in the documentation. What gives?

SOLUTION:

_xscale and _yscale properties have been replaced by scaleX and scaleY, which are both properties of the DisplayObject class. MovieClip (eventually) extends DisplayObject and inherits these properties.

The second snag is that scaleX and scaleY percentages are now divided by 100. Whereas before, MovieClip._xscale = 100 displayed the clip at its native width, MovieClip.scaleX = 1.0 is the new hotness.

MovieClip._xscale = 100; // Displays an object at its full width in Actionscript 2
MovieClip.scaleX = 1.0; // Displays an object at its full width in Actionscript 3

Take care when porting AS2 files to AS3.

PROBLEM: Pressing CTRL+SHIFT+ENTER to test your AIR movie in debug mode does not produce any results.

SOLUTION: What’s going on is that the Adobe AIR Debug Launcher did not shut down properly when you clicked the X (close gadget) on the AIR movie you were testing. Or, if your AIR app didn’t even have window chrome with a close gadget, you couldn’t shut the process down.

On a Windows system, open the Task Manager (CTRL+ALT+DEL) and click on the Processes tab. Find adl.exe and shut it down. Now you’ll be able to test your AIR app again without closing and relaunching the entire Flash IDE!

PROBLEM: Trace actions don’t appear in the output window when i test an Adobe AIR swf.

SOLUTION Instead of using CTRL+ENTER to test the movie, use CTRL+SHIFT+ENTER to debug the movie. i was lucky enough to catch a small footnote in the AIR documentation that mentioned this bug. In case you missed it, there’s your solution.

Proudly powered by WordPress. Theme developed with WordPress Theme Generator by Party Industries & Hogwarts Digital.
Copyright © untoldentertainment.com. All rights reserved.