Monday, February 28, 2011

Simple 2D Molehill Example

Simple 2D Molehill Example:

Here is a minimalistic FlashDevelop AS3 project that demonstrates how to use the Molehill API to draw a single 2D sprite on the screen. You can get the project here: fdproject-mole2d.zip.

To compile the example you need the Incubator version of the Flash Player, a new FlexSDK (“Hero”) and an updated playerglobal.swc which includes the Molehill API.
All files can be downloaded from Adobe Labs.
After downloading and unzipping the SDK to the folder {flexSDK} create a directory named “10.1″ in {flexSDK}\frameworks\libs\player\ and copy the new playerglobal.swc into it. Next fire up FlashDevelop and in Settings->AS3Context update the Flex SDK Location so it points to the new SDK. Finally just unzip & extract the FD project and hit F5 to compile.

Here are the basic steps to draw a textured quad:

  • Create a vertex buffer with 4 points to define a quad.
  • Create an index buffer that keys into this vertex buffer to define two triangles.
  • Create and upload a texture.
  • Compile the vertex and fragment programs (I’m using the AGAL mini-compiler from Adobe).

Then on every frame:

  • Assign the vertex and fragment program.
  • Transform the sprite and create a model-view-projection matrix for the vertex program. Since this is a 2D example we have to set up an orthographic projection.
  • Draw the triangles.

The mvp transformation could be done by the vertex shader but to keep it stupid simple I’m creating the matrix in AS3. Also note that we need to flip the y-axis and shift the origin to the upper-left corner [...]

How to Choose an ActionScript 3.0 Design Pattern Part 3: Shaking the Bag

How to Choose an ActionScript 3.0 Design Pattern Part 3: Shaking the Bag:

All our final decisions are made in a state of mind that is not going to last." –Marcel Proust Easing into a Selection Wouldn’t it be nice if you could type in the name of your intended project and up pops the best possible design pattern for that project? Even if you hold your breath until you turn [...]

Sunday, February 27, 2011

Changing the web, again. Flash Player with 3D API Molehill

Changing the web, again.:

Zombie Tycoon with Adobe Flash Player using Molehill

A few years ago, the Flash Player team introduced video in Flash Player, and today, we know how the Flash Player change the web for video on the web. Today, we are happy to introduce the public availability of the Molehill (3D GPU accelerated) APIs through the Incubator builds available here.

You cannot imagine how the team is excited to imagine what you guys will do with Molehill, definitely a game changer.

But first, what is this Adobe AIR and Flash Player Incubator thing ?

The AIR and Flash Player Incubator is a place for the Adobe Flash Runtimes team to share with developers features that are under development or experimental in order to get early participation, testing, and feedback from the community.  It is targeted at you guys that are interested in testing out the bleeding edge of runtime capabilities and contributing to the future of the platform. Keep in mind that the capabilities in Incubator builds may or may not be supported in a future release of the runtimes.

We will use the new Adobe AIR and Flash Player releases blog to share announcements about new Incubator builds. I will also relay the info here. For each new Incubator drop, we will highlight the features we are looking for feedback on. Incubator builds will contain features under consideration, development, or just experiments. By providing feedback on the features, use cases or things you will create, you will help us shape the future of the Flash runtimes.

As a developer, the Incubator program is extremely valuable, first, because you get to see features under consideration or development, but it also allows you to test your content against our builds. This way, you can track early in our development process if a current feature you rely on breaks, to make sure your content performs perfectly on the new version of the runtimes.

The Incubator builds are watermarked on the top bottom right of the stage, so that makes things easier to know if you are using an Incubator build or not.
Watermark for Incubator builds

Here are the key two features available in the first Incubator builds :

  • “Molehill” 3D APIs for Flash Player and AIR — A new set of low-level, GPU-accelerated 3D APIs that enable advanced 3D experiences across devices through the Adobe® Flash® Platform runtimes.
  • Cubic bezier curves — Using the cubicCurveTo drawing API, developers can easily create cubic beziers without custom ActionScript code required.
We worked closely with most popular ActionScript 3D frameworks so that anyone can get started with Molehill, not only advanced 3D developers. The following frameworks are already Molehill enabled today : [...]

Saturday, February 26, 2011

Flash Game Dev Tip #3 – Bullet Manager Part 1

Flash Game Dev Tip #3 – Bullet Manager Part 1:

Flash Game Dev Tip #3

Tip #3 – Flixel – Bullet Manager Part 1

If you are coding a shoot-em-up, or even a platformer with guns, then you’ll have a need for the player to be able to fire bullets. Or the enemies to fire at you. This tip is about creating a Bullet Manager class. The class is responsible for the launch, update, pooling and re-use of bullets.

Object Pool

Creating new objects in Flash is expensive. By “new objects” I mean code such as:

var bullet:Bullet = new Bullet();

… which creates a brand new object an assigns it to bullet.

And by “expensive” I mean it takes time for Flash to process the request for the new object, assign memory to it and create it. If you are firing off tens of bullets every few seconds this can take its toll. And if you don’t actively clean-up the objects created you can quickly run out of resources.

To mitigate this problem we create a “pool”. This is a pool of resources (in our case bullets) that the Bullet Manager can dip in to. It will look for a free bullet, and recycle it for use in the game. When the bullet has finished doing what bullets do best, it will free itself up for use again. By using a pool you avoid creating new objects on the fly, and help keep memory in check.

Meet FlxGroup

Thankfully flixel has a class you can use to make this process simple. It’s called FlxGroup. You can add objects to a group, there are plenty of  functions for getting the next available resource, and you can even perform group to group collision. Objects in a group are all rendered on the same layer, so are easy to position within your game. The first task is to create a pool of bullets to draw from.

In this example we’ve got a class called Bullet.as. Bullet extends FlxSprite with a few extra values such as damage and bullet type [...]

Wednesday, February 23, 2011

Cirrus service for developing end-to-end applications using RTMFP in Flash Player 10

Cirrus service for developing end-to-end applications using RTMFP in Flash Player 10:

Learn the benefits of using RTMFP in real-time communications, and use the new ActionScript 3 API to manage direct end-to-end RTMFP connections in a video phone sample app [...]

How to make a whole game in one day

How to make a whole game in one day:
There are game jams and Flash game competitions seemingly every weekend these days. While I don't really like the idea of pinning my eyes open with matchsticks and coding all night, I do like the idea of getting a complete game finished and released in a single day. I sometimes get a day or two of downtime between client projects, and rather than using this time to experiment on bunnies, I've been trying to work out how feasible it is to release 1 or even 2 games in these gaps.

My first couple of attempts have overrun by about double, and still aren't released (I'll keep you posted), but I have learned a few things along the way that I thought were worth sharing. I've also picked the brains of some other friendly developers for some suggestions (you know who you are, so thanks!)

Here's what I've worked out so far:
  • The game can't have more than 1 level that you need to design. So a single maze like Pacman would be ok, but you can't have every level be different.
  • You can't require any complex artwork. You need to use either free art, cheap stock art, art you already have kicking around, or art you can put together in 1 or 2 hours.
  • You need a game engine to start off with. Flixel and Flashpunk might work for you, but I prefer to use my own engine, which I have been revising and improving for well over a year. It's still nowhere near 'finished', but I'm not writing much low-level code for each new game.
  • You need a template .fla and/or FlashDevelop template already set up so you don't have to write any boilerplate for Mochi-ads, screen management, preloading etc
[...]

Monday, February 21, 2011

MochiLand: Islands of Empire: A Post-mortem

MochiLand: Islands of Empire: A Post-mortem:

my name is jay, this is my game
Hi, my name is Jay and I work at Mochi Media.  Islands of the Empire was the first (and only) game I have made.  So one day I was messing around with Flash and built this really cool map engine using Pixel Bender and was like, “Damn, I’m gonna build a game.”

URL: http://armorgames.com/play/10238/islands-of-empire
Source: http://github.com/jaybaird/Islands-of-Empire
Total Time: 18 months. :(

Step 1: Tech Demo != Game

July, 2009

My game, as it started out, was nothing but a tech demo. I wanted to see the interactions of Pixel Bender with different settings and filters to see if I could output little blobs of terrain on the screen. When I fired it up and out came the pretty pictures, I was sold. I was going to make this game.

A quick aside: I’ve been wanting to make games since, oh, about forever ago.

So where do we go from here? I’ve got islands. Do I make a game like Civilization? Risk? A long time ago I had aspirations to build something like Black & White and visions of awesome A-Life simulations and magic spells and wars and ships. Oh! Ships. I’ve got islands, let’s go nautical! What kind of boat games are there? I was drawn to Uncharted Waters and other games of the genre, even going so far back to Seven Cities of Gold. Then, over beers one night I was talking to Bob (yes, that Bob when I realized I wanted to see a nautical themed Galcon clone. That was it I decided. Galcon it is.

Step 2: Making Games is Fucking Hard

September 2009 – April 2010

Don’t worry too much about the language, cause for reals, this shit is hard. You guys impress the hell out of me day after day with what you’re able to do. So I had a map engine, I had a game design idea. Now it’s time to take the ball and run in for a touchdown, right?

No. Turns out I can make pretty graphics programmatically, but I suck at art. Ok, easy fix. I work with some of the most talented people ever so how do we solve this problem? We bribe Mr. Shen! Shen did an amazing job on all the in-game assets and I’m over the moon with the final look and feel. Shen. Is. Awesome. But you guys all know this.

So, once the art is out of the way, I start coding like mad in my spare time. I’m going crazy with Galcon style setups and balancing and grouping ships and having ships shoot at one another. That’s when the first bog hit. This game isn’t fun. It’s hard to control. The premise is shaky and I’m a terrible story teller, so I can’t talk my way out of this one. What to do. Hmm, I know! I’ll make an RTS! I’ve always wanted to write a pathfinder!

So I go down some awesome AI rabbit holes, I implement pathfinding, formations, blackboards and all sorts of fun stuff but never actually work on a game. This sinks in slowly. Co-worker and friend Bryon begins to only refer to the game as “the Tech Demo.

Step 3: There’s a Light On…

April 2010 – August 2010

[...]

Using Tweens with Box2D 2.0.1

Using Tweens with Box2D 2.0.1:

Juten tach,

i am currently involved in a fun project, where i am told to build a classical jump ‘n run game. Very nice. I am using the flash port of Box2d in its version 2.0.1. I know, that there is version 2.1, but it’s still alpha and i generally do not feel so comfortable using alpha software.

Like in most jump ‘n run games, we have moving obstacles, like little bricks, that move from left to right and back again and you have to jump on them to get over a giant abyss.

Now these moving bricks should move autonomously and indefinitely. Being a flash developer, first thing, that comes to mind is tweening them. But as we learn from many sources in the box2d community, this is actually a no-go, because we should rather use velocities and the real physics of Box2d to make things move. Makes sense to me.

So my first attempt was to reuse some of the smart scripts from Todd. And that worked quite well. Here is an excerpt of the script (actually with slight changes from my side) [...]

Summary of the Flash MindMeld

Summary of the Flash MindMeld:

Did you enjoy the Flash MindMeld?

If you want a brief recap of the conference, or you’re simply too lazy to listen for a 60 minutes speech, Chris Moeller from chrismweb.com listened all the tips and provided us a nice recap ready to be used when you are about to develop a game.

« I just finished listening and taking notes on all the sounds bites, and wanted to provide a summary of what I had heard.

I was happy to see Emanuele on there, but there were also some other big names, such as JIM GREER from kongregate, Sean Cooper who started game development in 1987, and worked on the PC title ‘Magic Carpet’ at bullfrom games, Tom Fulp, creator of newgrounds.com, alien hominid, Catle crashers, and many other developers, a lot I hadn’t heard of, but had seen their games.

Good Advice

Here is a bullet point list of what some of the developers said that I found useful:

  • Make games that are simple and quick. Don’s plan on spending a lot of time in development before seeing what people think of it. The advice ranges from spending 2hrs on programming, to spending two weeks to a month. This is good advice because you can find out whether a concept works relatively quickly, and can get feedback from people testing the concepts early on.
  • Make games re-playable by giving in game achievements and unlocking content- reward players for playing through multiple times. I think this is a good way to add re-playing because it gives casual players a way to get through quick, but also wonder about extra things in the game, and come back to try to find them, or even to have them feel like they ‘completed everything in the game’. Achievements aren’t too hard to add, but they can give a lot more for the player to do ‘if they chose to’(important part).
  • Make games social. Not just in trying to add in facebook API to ‘compete high scores with friends’, but also advice as throw something memorable in the game so your game stands out. make it easy for someone to describe your game to a friend, instead of it just being ‘another shooter game’. One example was a developer that made a game where a slug crawls into a cat box and explodes – since it was ‘unique’ crazy, it might be more memorable.
  • Have a good team. If you’re a great programmer, find a good artist and musician. This is something I’ve discovered is true in all sorts of business- outsource what you suck at, and work on what you’re good at. Sure, you can be good at everything, but it will save time, and allow each piece to be perfected by each person a little more if you can offload some of the work. Plus, spending a month trying to get a concept created and beign tired of the game vs. a week with a team means you’ll be less tired of the design, and able to think more creatively on your specific specialty.

[...]

Reuse Where Objects Change: Factory Method at Work with Lazy Instantiation

Reuse Where Objects Change: Factory Method at Work with Lazy Instantiation:

Gentle Readers: Chandima and I try different things, and this is the first time (I think) that we’ve taken an online Adobe Connect presentation and the accompanying PowerPoint slides and translated them into an article (post.) If you were able to attend the online talk, you have all of the slides along with written [...]

Flash Player 10.2 Performance: Part 2

Flash Player 10.2 Performance: Part 2:

Today’s article follows up on last week’s article that began by running many of the performance tests on this site with the newly-released Flash Player 10.2. Last week I got through half of the performance tests I did in my Flash Player 10.1 followup (see part 1, 2, 3, 4, 5, 6) and today I’ll [...]

Friday, February 18, 2011

Switch vs Strategy

Switch vs Strategy:

Recently, I’ve been working with the blend mode feature for Bunnyhill, my upcoming 2D rending engine based on Molehill. And I’ve used strategy objects to replace what could have been written in a switch statement. I think this could be a nice example for replacing switch statements with strategies, so I’ll share some of the details here.

The Switch Appraoch

First let’s take a look at the naive switch appraoch to set the blend mode of a render engine. Say we have a render engine that implements the interface below.

interface IRenderEngine {
 function setBlendMode(value:String):void;
}

And the BlendMode class provides static constants representing different blend modes.

class BlendMode {
 public static const ADD:String = "add";
 public static const ALPHA:String = "alpha";
 public static const NORMAL:String = "normal";
}

A possible render engine implementation for the switch approach is shown below.

class RenderEngine implements IRenderEngine {
 public function setBlendMode(value:String):void {
  switch (value) {
   case BlendMode.ADD:
    //use add blend mode
    break;
   case BlendMode.ALPHA:
    //use alpha blend mode
    break;
   case BlendMode.NORMAL:
    //use normal blend mode
    break;
  }
 }
}

In our main program, we could set the blend mode of the render engine like this.

renderEngine.blendMode = BlendMode.ADD;

The use of switch seems quite reasonable at the first glance, but is identified as “coding bad smell” in Refactoring, by Martin Fowler. If we were to add more blend modes to the render engine, this means we have to add an extra constant in the BlendMode class and an extra case in the switch statement. One feature change results in changes in two places, no good!

This is when the use of strategy objects should be considered.

The Strategy Approach

[...]

Thursday, February 17, 2011

Getting started with Ember

Getting started with Ember:

the Game

If your new to entity systems then you may want to read my posts on Game Architecture and Entity Systems first to get an over view. You can download the code for this example here

Ok so first step to making games on the Ember frame work is to create you games main class. This has the same role as an applications context in robotlegs.  Its main role is the initialization and tearing-down of you game.

package{
    import com.tomseysdavies.ember.base.Game;

    public class MyGame extends Game{
        override protected function startUp():void{

        }
    }
}

we can now launch the game from felx like so and pass it a reference to the display object that we want to become the games view.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:local="*">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
        <local:MyGame contextView="{gameView}" />
    </fx:Declarations>
    <mx:UIComponent id="gameView" />
</s:Application>

Components

So our game is now launching and has a reference to its view so we can now look at creating our first component. A component is a value object its highly portable and normal has no methods only data. For this tutorial we will need two.

package components
{
    public class PositionComponent
    {
        public var x:Number = 0;
        public var y:Number = 0;
    }
}
package components
{
    import flash.display.Bitmap;

    public class GraphicsComponent
    {
        public var asset:Bitmap;
    }
}

Entities

Now lets go back to our start up function. So here we first create that our components then next we create an entity and add our components to it. Think of an entity as an empty container to which we can add components. We create entities with the entityManager [...]

Entity Systems

Entity Systems:

Favour composition over inheritance

If you haven’t already read my previous post on the problems of traditional game architecture and why entity systems are needed. I’m going to cover the basics of an entity system before we look at 3 different implantations and the pro’s and con’s of each.

What is an entity?

An entity (sometimes called game object) represents something in the game. For every tree,tank or ninja we have an entity. An entity is container to which we can add components (behaviours) that define what it is. e.g In this rather conceptual example a Ninja gets a Renderer, Physics, Health and Stealth components which together make up a Ninja.

Entity system

This is the basics of all Entity systems one of key feature is the ability to create entities and change there components at run time. So a Ninja could become a Tank! (that’s the hard sell done).

Spotter guide.

There are 3 main ways to implement an entity system I have seen and I’m going to quickly out line them all and take a critical look at the pro’s and con’s. I’m going to call them common, almost and true (yes I’m bias but I think they are appropriate names)

“Common”

Most common implantation you are going to come across. Its based on the strategy pattern and its the simplest to understand. The first time I built a entity system this is what I did. There are good example out there in flash like PushButton Engine.

How it works

All components have a common interface normal with a function update(). Calling update() on entity causes update() to be called on all its components. Components then update there data for example a render component may copy its graphics to a view port.

Common Entity system

Pros

Simple and fast. Better than inheritance.

Cons

Scalability and flexibility (how easy it is to make changes). To explain the issue lets take an example. We have an entity with both renderer and physics components. Both need to know about the location of the entity in the world. So we have two options

  1. push the data up into the entity its self.  In complex games this can result inmore and more specialised data gets pushed up into the entity creating a god object.
  2. Allow components to access other components data. When one component depends on the data in another component we get a dependency. Component A can’t function unless component B exists. As a game grows so does the complexity of the dependencies.

There are work arounds to this issue for example automatically creating component B when A is added but then we need to give it the correct data. We start to lose the ability to mix and match components on the fly that makes an entity system so powerful. Entity to entity communication for example in collision detection is also difficult.

“Almost”

[...]

Rasmus Wriedt Larsen: CS4: Publish for FlashPlayer 10.2

Rasmus Wriedt Larsen: CS4: Publish for FlashPlayer 10.2:

So, flash player 10.2 was just released!

It features StageVideo, Native Mouse Cursor and the ability to view full screen flash content on one screen, while working on the other!

So these are some really cool features! But how do people with CS4 get their hands on these? Adobe is not likely to publish an update to CS4 that enabled us to do this, at least they didn’t with FP 10.1!
(...)
Read the rest of CS4: Publish for FlashPlayer 10.2 (259 words)

Quick Tip: Displaying a 3D Model With Papervision3D

Quick Tip: Displaying a 3D Model With Papervision3D:

In this Quick Tip we’ll take a look at how to embed and display a 3D model in Flash, using Papervision3D.


Final Result Preview

Let’s take a look at the final result we will be working towards:


Introduction

To use this tutorial you will need to have a 3D model, exported as a .dae file, and its texture, as an image file.

I’m going to be using this low-poly mountain bike model from 3DOcean, created by OneManBand (who also created this neat 3D Object Viewer in AIR).

You will need to download a copy of Papervision3D (you can also find a copy in the source files)


Step 1: Creating the Flash File

Create a new ActionScript 3 document with dimensions of 550x200px and set the frame rate to 30fps. Also, set the document class to “EmbeddingDAE”.

Create a rectangle that covers the whole stage, and fill it with a radial gradient of #FFFFFF to #D9D9D9. Adjust the gradient with the Gradient Transform Tool, so it looks like this:

Rectangle

Step 2: Setting up the Document Class

Create a new ActionScript 3 file and name it “EmbeddingDAE”. This class will extend a class from Papervision that has all the basic functionality set up.

As we’re going to be embedding the 3D model in your SWF, we need to make sure the file has been fully loaded before trying to make use of it.

Here is the code for that:

package
{
 import flash.events.Event;
 import org.papervision3d.view.BasicView;

 public class EmbeddingDAE extends BasicView
 {

  public function EmbeddingDAE()
  {
   this.loaderInfo.addEventListener ( Event.COMPLETE, onFullyLoaded ) ;
  }

  private function onFullyLoaded(e:Event):void
  {

  }

 }

}

Step 3: Embedding the Resources

Instead of hosting our resources at a webserver and loading them from there, we’re simply going to embed them in the SWF. We do this by using the Flex SDK Embed tag. If you don’t have the Flex SDK, or are having trouble with the pre-installed version, you can download it here

Flash knows how to deal with certain types of files, like my .png texture file, but it doesn’t know the .dae file format. Therefore we have to set a secondary parameter, the MIME type, to application/octet-stream – this means the file will be transformed into a ByteArray.

When using the Embed tag, we need to be referring the relative (or full) path of the file, and assigning a class to this file. Later we can create an instance of the embedded file using this class.

Here you can see the code:

public class EmbeddingDAE extends BasicView
{
 [Embed(source="mountain_bike.dae", mimeType="application/octet-stream")]
 private var bikeModelClass:Class;

 [Embed(source="bike_texture.png")]
 private var bikeTextureClass:Class;

 public function EmbeddingDAE()

You will need to replace the paths so they match your own files [...]

How to communicate between game objects.

How to communicate between game objects.:

Over on Richard “PhotonStorm” Davey’s blog he proposed a simple way to communicate between objects in your game using a “Registry” a class with static variables storing all the major systems of your game. So, for example if you wanted to create a spray of blood when an enemy is hit, in the enemy’s hit() function you would include the line Registry.fx.sprayBlood(x, y) and the FX object stored in the Registry.fx variable would create the blood spray and handle updating etc.

In the comments on Richard’s post, I pointed out that this isn’t a very object-oriented approach: these are basically global variables by a different name. I have used a similar approach myself on quite a few games projects, and overall it works well and is a quick way of getting things done. I have, however, encountered two problems with it.

Firstly, you can end up with all you code in one huge blob or “god class”. For example, if the FX class is responsible for handling any possible visual effect you would want to create, it could end up getting very big. But, other than academic notions of “good” and “bad” code, there’s nothing especially wrong with having big classes. They may be a bit harder to maintain and reuse, but nothing to worry about too much.

Secondly, using static/global variables as a communication method means you can be limited to having only one “game” in a single project. Now in most scenarios this wouldn’t be a problem, but it’s normally best not to assume you will only ever have one of a particular class of object. I’ve worked on several Flash projects that were collections of minigames in a single swf. Where I was relying on static variables in some of my base-classes and utility classes, I started to see clashes between the different games.

Ok so how do I handle the same problems? Well, say an enemy needs a reference to the player in order to chase after them. Rather than looking up Registry.player, I would just have a “player” variable in my enemy class and I would pass in the value of player when I create the enemy, or once I know the player exists. Or if the enemy needed more than a couple of different references from game in order to work, I would just pass in a reference to the game itself, and let the object access whatever information it needs. As Richard points out, the downside to this approach is that you end up with a lot of references in different places. This isn’t really a problem if you null your references when destroying objects, but it is more work, and you can leak memory if you’re sloppy with it [...]

Tuesday, February 15, 2011

Flash Player 10.2 Performance: Part 1

Flash Player 10.2 Performance: Part 1:

From a performance perspective, lots changed in Flash 10.1 (see part 1, 2, 3, 4, 5, 6). Flash Player 10.2 was officially released last week, so it’s time to update this site’s many performance tests to the new player. This time around I’ll be updating more performance tests per part of this series, so hopefully [...]

Exchange data between Actionscript 3 and Javascript - communication bridge

Exchange data between Actionscript 3 and Javascript - communication bridge:

Today we will learn how to exchange data between Actionscript 3 and Javascript, we will create a communication bridge using the ExternalInterface class.

In my example, there is going to be a numeric value in flash, which can be increased using javascript code.

Firstly, create a textfield in flash called myField and a button called myButton.

Here is the code for the flash file:

var myVar:Number = 0;
myField.text = myVar.toString();

ExternalInterface.addCallback('sendToAS', getFromJS);

function getFromJS(dir):void
{
myVar += dir;
myField.text = myVar.toString();
}

myButton.addEventListener(MouseEvent.CLICK, sendToJS);

function sendToJS(MouseEvent):void
{
ExternalInterface.call('receiveAS', myVar);
}

We use 2 methods of ExternalInterface class - call and addCallback. The addCallback is used for receiving stuff from JS, for example, the JS code asks the flash to perform a 'sendToAS' action. The flash receives the request and then looks at it - if the request is 'sendToAS', then perform a function called getFromJS [...]

60 mins of Game Dev advice from 60 speakers at FlashMindMeld

60 mins of Game Dev advice from 60 speakers at FlashMindMeld:

Flash MindMeld 2011

A month or so ago David Fox contacted me asking if I’d be willing to submit a 60-second recording, answering the question “What makes or breaks a great flash game?“. Apparently 59 other speakers were also on-board. So I figured with those kind of odds at least the listeners could have a giggle at my “speech” and move onto something more inspiring. So I agreed.

David put a butt-load of work into the event. Collecting all the samples, organising everything and putting the site together. And today it’s finally all live! You can listen to some great snippets from the likes of Adam Saltsman, Tom Fulp, Edmund McMillen, Rob James, Stephen Harris and a load more. And when you’ve exhausted all of their brilliance you’ll find me. Apologies in advance for sounding like a teenager sniffing glue. You’d never have guessed my Dad was a radio DJ and my Mum a singer. Voice talent skipped my generation :) (I got the geek strain instead, so a fair trade)

Hopefully David will run the event again, with a new question and maybe another set of 60 speakers, as the concept is a great one. And of course thanks to Ilija for pixelating me. I think. (I do actually have a neck tho!)

Find everything you need at http://www.flashmindmeld.com/

Sunday, February 13, 2011

Flash Game Dev Tip #1 – Creating a cross-game communications structure

Flash Game Dev Tip #1 – Creating a cross-game communications structure:

Flash Game Dev Tips

Tip #1 – Flixel – Creating a cross-game communications structure

As moderator of the flixel forums there is one question I see time and time again. It starts something like this: “how can I make X talk to Y, especially when the State changes?”. The problem is a classic OOP one, and thankfully there is a classic OOP approach to solving it. Have a look at the following diagram:

Game state diagram

Here we have part of a mock-up Game State structure for an RPG game. As part of the state you can see the Player, an Enemy Manager, an Inventory (which both Player and Enemy can share) and a Map consisting of several important locations.

Of course this is just a rough-example, so don’t get bogged down in the semantics or structure of it. Instead think about how inter-dependant all of these objects are on each other.

  • For example perhaps the Temple won’t allow the Player to enter if he is carrying a weapon.
  • What if when fighting the Thief you win, but he steals a Potion from your Inventory before running away.
  • Perhaps the enemy wouldn’t even attack you if he realised what Sword you were carrying?
  • A Wizard casts a fireball at you. How much of the damage does your Armour repel?

In all but the most simple of games it’s vital that your game objects can communicate with each other. And communicate effectively.

When you create your Game State you could first make the Player object, and then pass a reference of that into say the Enemy Manager, so the baddies it creates can check out your vital stats prior to attack. But passing references around like this gets messy, and it’s all too easy to leave “open ends” that don’t get cleared up as needed. In a worse-case scenario they could leak memory and crash Flash Player. And in a “best case” they just confuse you during development.

One Ring to Rule Them All

My suggestion is to use a Registry. A Registry is “A well-known object that other objects can use to find common objects and services.” (Martin Fowler, P of EAA) – sounds ideal, right?

They are extremely easy to create too. In your Project create a file called Registry.as – Here is an example file based on the structure above: [...]

How to Choose an ActionScript 3.0 Design Pattern Part 2: Avoiding Redesign

How to Choose an ActionScript 3.0 Design Pattern Part 2: Avoiding Redesign:

"strong>What are the causes of System Redesign? To get started on Part 2 of choosing a design pattern, we need to look at the causes of redesign. I realize that his is jumping ahead in the list, but because the issue of re-design is at the heart of design patterns, it’s a good place for the [...]

Friday, February 11, 2011

Matrix Stack and the Visitor Pattern

Matrix Stack and the Visitor Pattern:

Scene Graphs and Scene Trees

When building a scene graph framework, such as the display list in ActionScript 3.0, two types of nodes are involved: internal nodes and leaf nodes. The transformation properties (x, y, rotation, etc.) are passed down from parents to children; that is, if the parent’s local coordinate is (10, 10), and a child’s local coordinate is (5, 5), then the global coordinate of the child is (15, 15).

ZedBox, my 2.5D billboard engine, internally manages objects in scene tree structure (a more specific type of scene graph where each child can only have one parent), just like the display list structure in ActoinScript 3.0. Each node holds a reference to an object containing its global transformation. When the scene tree is traversed in the render routine, the global transformation of each node is updated by its parents; in other words, the global transformation of each node is updated recursively from the root down.

Back then, this seemed to be a very reasonable approach to me. Later, however, I found out that this approach eventually made my code very messy and hard to maintain. Also, this approach does not apply to scene graphs; since in a graph each node can have more than one parents, it’s not right to have each node to hold reference to a single global transformation of its own. After a having a little chat with Jean-Marc Le Roux (the author of Minko 3D engine), I got to know that he used the Visitor Pattern in Minko to traverse the nodes managed in scene graph structure. Suddenly, it had struck me that this pattern is the key to calculate global transformation of the nodes in a scene graph. Instead of storing the global transformation of each node in the node itself, each node can have a chance to access the visitor when the visitor visits the node, where the visitor holds a reference to a matrix stack.

Matrix Stack

A matrix stack is essentially, well, a stack that contains matrices (here a matrix represents spatial transformation). The interface of a matrix stack may look like this [...]

Thursday, February 10, 2011

Freelance Flash Games News: Want your Shot at $10,000 in Prizes?

Freelance Flash Games News: Want your Shot at $10,000 in Prizes?:

If your looking to bring in some extra cash, take a look at the 2nd Games that Challenge World Contest. Brought to you by the social gaming site Come2Play and the Flash Game Developers group on LinkedIn, the contest will award prizes for the top 4 games built using Come2Play’s Multiplayer API. But before I get [...]

Wednesday, February 9, 2011

Adobe Flash Player 10.2 is live!

Adobe Flash Player 10.2 is live!:

Adobe Flash PlayerThere we are, I am happy to announce that the Adobe Flash Player 10.2 is live since a few minutes. (Debugger builds available here)

I covered the list of features a few weeks ago, Flash Player 10.2 ships with Stage Video for high performance video playback and also the very cool native mouse cursors feature that game developers will love but also some performance optimizations with IE9 and also text quality improvements on mobile. With Flash Player 10.2, you can also enjoy fullscreen on one screen while you keep working in the other screen, pretty cool for the video people. Keep in mind we will keep working on little improvements like this in future releases, to always enhance the user experience with the Flash runtimes.

I wrote two articles so that you guys can get started easily with Stage Video and the Native Mouse Cursors. I hope you will enjoy playing with those features. To author for 10.2, just use the latest Flex Hero SDKs available on opensource.adobe.com (4.5.0.18623 or 4.5.0.19786) [...]

Sunday, February 6, 2011

How to Choose an ActionScript 3.0 Design Pattern Part 1: Understanding the Fundamentals

How to Choose an ActionScript 3.0 Design Pattern Part 1: Understanding the Fundamentals:

"strong>Which Design Pattern? One of the most persistent questions that we get is, How do you select a Design Pattern?, and usually, my response is, Decide what varies and see which pattern handles that variation. Of course, we find that lots of things vary, and deciding which one to build a design pattern around can be [...]

Saturday, February 5, 2011

Quick Tip: Test Your Movie in Different Flash Players with FireFox

Quick Tip: Test Your Movie in Different Flash Players with FireFox: "

Flash Player is a plugin that is constantly upgraded, and it could be necessary to check your project is compatible with different versions. We’ll look at how to do it quickly with the Flash Switcher tool.


Step 1: What is Flash Switcher?

Flash Switcher

Flash Switcher is a Firefox extension which lets you switch between different Flash Player versions quickly and easily.

It comes with various Flash Player versions and it can be activated right in the browser.


Step 2: Requirements

FlashSwitcher add-on for Firefox

To use Flash Switcher you will need Firefox 3.0a1 or later. You may encounter problems with the installation depending on your browser version; this can be solved by installing the extension from the author’s site, as in the next step.


Step 3: Download it!

You can get Flash Switcher using the Mozilla add-ons website, although I recommend downloading it at the author’s site for better compatibility and support.


Step 4: Testing

[...]

Wednesday, February 2, 2011

FlashGameLicense Blog: Monetizing Your Web Game Part 1

FlashGameLicense Blog: Monetizing Your Web Game Part 1:

Monetizing Your Web Game Part 1

Currently there are many choices when it comes to monetizing a web game. It can be daunting to decide which model is best for a developer. On top of this, there are conflicting reports as to which ones are truly lucrative. The hope of this series of articles is to shine a light on many of the monetization methods to choose from by presenting hard facts based on case studies from a number of developers as well as statistics we have been tracking at FlashGameLicense.com and GamerSafe.com.

Part 1: Sponsorship and Licensing

Before I get into the ins and outs of licensing a web game, let me define some terms:

Sponsorship

  • A deal made between an entity (the sponsor) and a developer in which the sponsor pays to have their branding/ads in one of the developer’s games. The terms Sponsorship and License are used interchangeably in most cases (and in all cases for the purposes of this article).

Primary License/Sponsorship

· A sponsorship where the Sponsor has their branding in every copy of the game on the web except where the developer has explicitly sold a Secondary License (defined below) to another entity. The developer has complete freedom to remove the primary sponsor’s branding and make any other changes to the game as long as it is licensed and locked to the other entity’s domain.

Non-Exclusive License/Sponsorship

· A Sponsorship where the license of the game is not exclusive to the buyer. The buyer is purchasing one custom version of the game.

Secondary License (aka Non-Exclusive Site-Locked License)

· A Sponsorship where the license of the game is not exclusive to the buyer. The buyer is purchasing one custom version of the game, and this version must be “locked” to the buyer’s domain. This is the most common type of non-exclusive license and it is compatible with the primary license.

Performance Bonus

· A bonus paid by the Sponsor to the Developer based on pre-defined performance milestones. Bonus structures take many forms. A couple of examples are: a lump sum payout if a game gets a certain number of plays, or a CPC (cost per click) deal where the Developer is paid for each unique user sent back to the Sponsor’s site.[...]

Tuesday, February 1, 2011

PatternCraft – Chain of Responsibility – Part 1

PatternCraft – Chain of Responsibility – Part 1:

PatternCraft is a series of video tutorials that use StarCraft references to teach Design Patterns. Source available here: https://github.com/johnlindquist/johnlindquist.com/tree/master/ChainOfResponsibility-ATM