Thursday, October 25, 2012

Joe Willmott's Blog: Flash AS3 camera to follow your character

For years I have used Sham Banghal's vCam in my flash games. It has always done what I needed of it and it was easy to use, however my latest game is a big one and as a result, it creates a decent amount of lag. I have looked into it and the lag was caused by all of the complex vector graphics. A way around this was to make a new camera that only rendered the graphics that are currently on-screen, saving the computer from having to render everything all of the time. I used scrollRect to create the simplest of cameras and would like to share it with anyone else looking for a very simple camera to use in their flash games! The only code required is this:
import flash.events.Event; import flash.geom.Rectangle; stage.addEventListener(Event.ENTER_FRAME, cameraFollowCharacter); function cameraFollowCharacter(evt:Event){ root.scrollRect = new Rectangle(char.x - stage.stageWidth/2, char.y - stage.stageHeight/2, stage.stageWidth, stage.stageHeight); }
As you can see from the code, you will also need a movie clip on-stage called "char" (or if it is called something else, change the bits that say "char" in the code. This is an incredibly simple camera but very effective as it completely removed the lag from my game! I have also attached an example .fla so you can see how it all works (saved in Flash CS4): Source file: Joe Willmott's ActionScript 3.0 Camera

read more: Joe Willmott's Blog: Flash AS3 camera to follow your character

Monday, October 22, 2012

Picking a Color Palette for Your Game’s Artwork

In this tutorial, we’ll look at what color palettes are, tools for choosing colors that go together, and the secret to picking a perfect color scheme for our games!

An Introduction to Color Palettes

The term color palette is used widely across many different industries of design. Its exact definition and interpretation varies slightly between industries, but for the purposes of game design we can simply refer to it as a predefined set of colors based on specific rules.
Traditional color palettes generally consist of five colors within a specific scheme, but this is more of a guideline than a rule. In game design, color palettes can consist of any number of colors as long as they all follow your predefined set of rules.
Before we delve deeper, consider whether you want to create your own color palette or find a ready-made scheme online. Either way, there are many tools that can help you out!

Picking Palettes With Tools

Color palettes can be created in virtually every program with a color picker, but why use MS Paint when there are so many great websites that can get the job done better?

Kuler

Adobe Kuler is one of my favorite tools for making a color palette, simply because it acts as an all-in-one tool.
As well as being able to create your own color palette and pick colors from an image you find inspirational, you can also share your palettes and find ones created by others! This means there’s a never-ending supply of ready-made palettes for you to choose from.
I recommend using this tool if you are looking for an in-depth experience or if you are looking to find user palettes created by others.

Color Scheme Designer 3

Another great tool for making color palettes is Color Scheme Designer 3. It has all the standard features you would expect from a color palette tool, and really shines in in its interface design!
I found it effortlessly easy to jump in and make a color palette. I would recommend using this tool if you are looking for a simple experience.

Color Blender

The last tool I am going to suggest is Color Blender. Out of the three tools I would have to deem this tool the most interesting.
Read more: Picking a Color Palette for Your Game’s Artwork

Friday, October 19, 2012

Stage3D compressed textures – Introducing the ATF SDK

We introduced Stage3D last year and the momentum behind has never stopped growing but there is one area we did not give all the details. The ATF file format, it is mentioned here and there, so what's up with this? Some of you may have seen it in the documentation for Stage3D referred as the compressed texture file format, but we never shared any tools to create those famous ATF textures.
Before we package the ATF tools with the AIR SDK, I am happy to share here in advance the ATF tools so that you guys can start leveraging the ATF format now!
So what is it?
First, let's start by talking about what compressed textures are.
When doing GPU programming with any technology, you have two options for how you handle your textures. You can go compressed or uncompressed, very simple. So, what is the difference?
  1. When using uncompressed textures, a good old uncompressed file format like PNG is used and uploaded to the GPU.
  2. Because GPUs don't support such a file format natively, your texture is actually stored in CPU memory, when it could actually be stored on the GPU memory!
  3. Same thing applies for JPEG images, make no mistake, graphics chipsets don't know anything about JPEG which would also be decoded on CPU memory.
  4. Of course, each platform has different support for compressed textures depending on the hardware chipset being used.
Now get ready for the fun! Here is below a little table to illustrate it:

PlatformFormat
ImgTech (iOS)PVRTC
Qualcom (Android)ETC1
Mali (Android)ETC1
NVidia (Android)ETC1/DXT1/DXT5
Android (PowerVR)PVRTC/ETC1
WindowsDXT1/DXT5
MacOSDXT1/DXT5


Why ATF?
As you can imagine, if you would develop a game targeting iOS, Android and desktop, you would need to supply your textures compressed to each format for each platform. Which would look like this:
  1. leaf.png encoded to DXT for Windows and MacOS
  2. leaf.png encoded to ETC1 or DXT for Android (Nvidia)
  3. leaf.png encoded to PVRTC for iOS (ImgTech)
Of course it is a pain to provide all the different versions of the textures, detect at runtime which platform you are running on and upload the corresponding texture. Wouldn't it be cool if you could just rely on one single container, that would wrap all the textures for each platform and Flash Player or AIR would extract automatically the texture required depending on the platform? So here comes ATF.
The ATF internals
Really, think about the ATF format as a container for lossy images. Here is below a little figure showing very sinply the structure of a default compressed ATF file:
Read more: Stage3D compressed textures – Introducing the ATF SDK

Wednesday, October 17, 2012

Project “Monocle”, profiling taken to the next level

Adobe project "Monocle"Back in August, I posted a sneak peek video of project "Monocle" the next-generation profiling tool for ActionScript based content. Last week at GDC online, I gave a talk entitled "Changing the game" and demoed Monocle. Again, the feedback we had was unbelievable.
I have been using Flash for 13 years now and I have seen lots of cool things happening in Flash. The introduction of AMF in Flash Player 6 (Flash Remoting) allowing fast and efficient RPC communications taking care of serialization for you (AMFPHP, anyone? Props to Patrick Mineault). Damn, that was nice. The introduction of BitmapData in Flash Player 8, which enabled so much expressiveness and Flash Player 9 with ActionScript 3 and a world of new possibilities. I think Monocle is the next big thing happening to Flash, it will just revolutionize the way we work with Flash Player and AIR.
I got lots of emails and tweets from people asking to get on the prerelease. I am really excited to announce that all of you guys can now get access to "Monocle"!
Please register, test Monocle, look for bugs, give us feedback! So what do you need to get started?
1. Register here.
2. Download Flash Builder 4.7 Game Development Beta 2 with Project Monocle Support.
3. Compile your project and make sure the compiler option "Enable Detailed Telemetry" is enabled. Joseph Labrecque has posted great details here.
4. If you are using Flash Pro or have existing SWFs you don't want to recompile. We provide a little python script to post process you SWF and make them profilable.
I hope you guys will love it. Enjoy!
Read more: Project “Monocle”, profiling taken to the next level

Getting all the collection names with MongoDB and AS3

At work I've been making on a quick tool to modify objects in MongoDB for our upcoming game. As I remembered reading about some AS3 drivers that allow you to directly connect to a Mongo database rather than need to use a server script, I decided to take a look. And immediately hit a roadblock.
In the main libs I found; @s9tpepper's MongoAS3 lib, and JMCNet's full-mongo-flex-driver; there was no built-in way to get the collections in a database. If you've worked with Mongo before, you'll know that it's slightly important to know that.
Both libs provided access to the Mongo runCommand() command, but no combination of keys seemed to do the job. Of course, you could always just keep a static Array of Strings, but where's the fun in that?
Other languages and drivers usually have a function along the lines of getCollectionNames() and with the help of @dun4n's google-fu, we found out how to do it. Mmmm, smells like a hack!

How it works

So, for a database that looks like this: [...]
Read more: Getting all the collection names with MongoDB and AS3

Tuesday, October 16, 2012

Create a Simple Asteroids Game Using Component-Based Entities

In the previous tutorial, we created a bare-bones component-based Entity system. Now we’ll use this system to create a simple Asteroids game.

Final Result Preview

Here’s the simple Asteroids game we’ll be creating in this tutorial. It’s written using Flash and AS3, but the general concepts apply to most languages. The full source code is available on GitHub.

Class Overview

There are six classes:
  • AsteroidsGame, which extends the base game class and adds the logic specific to our space shoot-’em-up.
  • Ship, which is the thing you control.
  • Asteroid, which is the thing that you shoot at.
  • Bullet, which is the thing that you fire.
  • Gun, which creates those bullets.
  • EnemyShip, which is a wandering alien who’s just there to add a bit of variety to the game.
Let’s go through these entity types one by one.

The Ship Class

We’ll start with the player’s ship: [...]

Read more: Create a Simple Asteroids Game Using Component-Based Entities

Monday, October 15, 2012

TypeScript for ActionScript Developers

Introduction

The following covers what the TypeScript language is compared to ActionScript 1, 2, and 3 with as much context as possible and compares the syntax side by side. This article should help serve as a reference while you learn TypeScript. Also, these articles always help me learn while writing them and I like to have documentation I can refer to later.
You cannot really talk about ActionScript without talking about the Flash Player internals just like you can’t really talk about JavaScript for web development without also talking about browser internals. Thus, I’ve tried my best to make what the ActionScript equivalents are in the JavaScript browser world.


What is TypeScript?

TypeScript is awesome. It’s this new language from Microsoft that enhances JavaScript. Like Robert Penner said, it’s basically ActionScript 2. You get strong-typing at compile time, but your code is compiled to ActionScript 1/JavaScript at runtime and has no enforcement of types. It has a variety of features, but the only two that really matters are the optional strong-typing and the ability to work with existing JavaScript libraries in a strongly-typed way. There are more, but the only ones ActionScript developers will really care about are:
  1. Optional Typing
  2. Classes
  3. Packages via Namespaces
  4. supports private
  5. modules
  6. everything compiles to JavaScript
  7. everything using classes/packages/modules compiles to RequireJS/AMD/CommonJS
  8. You can code in normal JavaScript; TypeScript is optional; you can mix and match
  9. all the TypeScript features for typing aren’t compiled into JavaScript (no enforcement) so it’s normal JavaScript that gets outputted
Again, there are some other cool features such as overloading, interfaces, statics, follows ECMAScript 6, allows you to “use” ECMAScript 6 now, open source, blah blah blah, etc. I’m only focusing on that ones that matter.
Here its creator, Anders Hejlsberg of Turbo Pascal, Delphi, and C# fame, does a 1 hour overview.



Anders Hejlsberg

Why TypeScript?

If you want strong-typing in JavaScript, you’ll love TypeScript. Its typing is near identical to ActionScript 2 and 3.
If you are a server-side developer who prefers to render the client side, think Google Closure annotations are sufficient, unit tests who’s sole purpose is to catch spelling errors & type casting errors, or believe “loose typing” is a great feature of JavaScript, peace the eff out.
To quote Cliff Hall on a recent post defending languages that compile to JavaScript on Google+:
They let you apply useful abstractions like classes, interfaces, inheritance, encapsulation, and OOP design patterns. This allows you to build larger systems in a more maintainable way, that is more team-friendly.
Yep. For me, spelling mistakes and type issues that aren’t parsing related should be trivial issues, but instead have a major detrimental impact because of the current JavaScript development landscape and browser runtime issues (swallowed exceptions, misleading error messages, still not developer friendly compared to more mature runtimes, etc). TypeScript, at least in Visual Studio, will help alleviate the spelling & type casting issues, and if you do write unit tests, they’ll test more important things.

How? TypeScript Compiler

TypeScript the compiler is written in TypeScript. The compiler will output to JavaScript, optionally with header definitions. If you go to http://www.typescriptlang.org/ you can learn how to install and/or download what you need. I used the Node install. For Mac, this is nice because it makes it global so you can play in the Mac Terminal.
npm install -g typescript
If you want to compile some TypeScript to a JavaScript file in the same directory, on a command line, go: [...]
Read more: TypeScript for ActionScript Developers

Avoiding the Blob Antipattern: A Pragmatic Approach to Entity Composition

Organising your game code into component-based entities, rather than relying only on class inheritance, is a popular approach in game development. In this tutorial, we’ll look at why you might do this, and set up a simple game engine using this technique.

Introduction

In this tutorial I’m going to explore component-based game entities, look at why you might want to use them, and suggest a pragmatic approach to dip your toe in the water.
As it’s a story about code organisation and architecture, I’ll start by dropping in the usual “get out of jail” disclaimer: this is just one way of doing things, it’s not “the one way” or maybe even the best way, but it might work for you.  Personally, I like to find out about as many approaches as possible and then work out what suits me.

Final Result Preview

Throughout this two-part tutorial, we’ll create this Asteroids game. (The full source code is available on GitHub.) In this first part, we’ll focus on the core concepts and general game engine.

What Problem Are We Solving?

In a game like Asteroids, we might have a few basic types of on-screen “thing”: bullets, asteroids, player ship and enemy ship. We might want to represent these basic types as four separate classes, each containing all the code we need to draw, animate, move and control that object.
While this will work, it might be better to follow the Don’t Repeat Yourself (DRY) principle and try to reuse some of the code between each class — after all, the code for moving and drawing a bullet is going to be very similar to, if not exactly the same as, the code to move and draw an asteroid or a ship.
So we can refactor our rendering and movement functions into a base class that everything extends from. But Ship and EnemyShip also need to be able to shoot. At this point we could add the shoot function to the base class, creating a “Giant Blob” class that can do basically everything, and just make sure asteroids and bullets never call their shoot function.  This base class would soon get very large, swelling in size each time entities need to be able to do new things. This isn’t necessarily wrong, but I find smaller, more specialised classes to be easier to maintain.
Alternatively, we can go down the root of deep inheritance and have something like EnemyShip extends Ship extends ShootingEntity extends Entity. Again this approach isn’t wrong, and will also work quite well, but as you add more types of Entities, you will find yourself constantly having to readjust the inheritance hierarchy to handle all the possible scenarios, and you can box yourself into a corner where a new type of Entity needs to have the functionality of two different base classes, requiring multiple inheritance (which most programming languages don’t offer).
I have used the deep hierarchy approach many times myself, but I actually prefer the Giant Blob approach, as at least then all entities have a common interface and new entities can be added more easily (so what if all your trees have A* pathfinding?!)
There is, however, a third way…

Composition Over Inheritance

If we think of the Asteroids problem in terms of things that objects might need to do, we might get a list like this: [...]
Read more: Avoiding the Blob Antipattern: A Pragmatic Approach to Entity Composition

Saturday, October 13, 2012

SWF Versioning

I am sure some of you guys have been confused in the past about the SWF versioning and which version to use when targeting Flash Player or AIR. Romil in the past posted a little table with the history. I decided to give it a little update that you can then bookmark. We will have this posted as an official reference on livedocs soon, but for now here it is!
Flash Player versionAdobe AIR versionSWF version
9.0.115.0NA9
10.01.510
10.12.010
10.22.611
10.32.712
113.013
11.13.114
11.23.215
11.33.316
11.43.417
11.53.518

Read more: SWF Versioning

Tuesday, October 9, 2012

How to make a multi-player game – part 1

Hello and welcome back to my blog!
Its been a while since my last post, this is because I’ve been working on a multi-player game, called mmoAsteroids which you can play by clicking on the icon on the side-bar. This post is my attempt to crystallise the most important points I’ve learned during the making of this game and my other multi-player prototypes.

Click here to view the video on YouTube.

Introduction

Firstly, it’s important to identify what I mean by multi-player and what implications that has. I’m talking about non-local multi-player, over the internet rather than at the same computer.
Of course this means there needs to be some kind of way for the players to communicate with each other over the internet. I’ve chosen the server-client model rather than peer-to-peer, because that’s what my target platform client, Adobe Flash supports.

Client side

Why choose Flash? Because:
  • The install base is massive, even compared to HTML5
  • It’s a fixed platform, you don’t need to worry about different browsers, or different hardware
  • The Flash portals are an amazing resource for distributing games
  • There are very mature development environments available which support full debugging via the world class Visual Studio
  • It has support for TCP sockets built right in

Server side

Because I’m using the client-server model, I need to choose a platform for the server-side code.
I’ve chosen node.js for this article, simply because it’s the fastest way to get a decently performing server set up and running with the least amount of code. Also, with your own server there are no limits on the number of clients you can support simultaneously, unlike ready made packages like player.io, or SmartFoxServer which limit you to a certain number of users until you sign up to their paid plan.
Of course, they provide a lot more features for that money as well; it’s important to weigh up the costs and benefits of whatever platform you choose.

Client-server model

How do server-client based multi-player games work?

Briefly, the client and server communicate by sending messages to one another. The client might send a message to the server saying he wants to move forwards. The server will receive the message and react accordingly. The server might send back a message saying that the player collected a power-up, or that someone else has joined the game.
The client and server both maintain a copy of the game universe; the server has the master copy and then client has a (possibly partial) copy for local simulation and display purposes. The server has authority over all the important decisions in game, like players getting hit by bullets, or being killed, or levelling up. The client has authority about what keys are being pressed and other pieces of user input data.
The reason for this separation of authority is to prevent cheating; although this is only really something you need to worry about once your game is big enough for hackers to invest time in finding cheats, it’s worth taking simple steps ahead of time to prevent the possibility of a hacked client from, for example, transmitting that he killed everyone in the world to the server, or something of that nature.
Having the server be in authority simply prevents this from being possible.

WoW recently suffered from hackers exploiting the system

MMO? MO?

It’s important to distinguish between the various types of multi-player game before we get into this too deeply, because the type can have a massive effect on the amount of code you need to write.
Starting at its simplest form, I’m going to define an MO or Multi-player Online game as a multi-player game supporting as many players as possible running on one server (a physical computer located on the internet somewhere).
An MMO is a Massively Multi-player Online game. There are many different forms this can take, but nearly all of them will involve more than one physical server working together to handle the huge load that ‘massively’ implies.
How they work together will define how the game is to be designed; for example you might want your game universe to be shared by all players at the same time, as in Eve Online; this requires that several servers work together to form a large shard to share the load. Or you might want to instance your universe so that each individual server actually holds a unique copy of the universe and players in one universe cannot see players in another, like Realm of the Mad God. Or yet again, maybe you want to have some kind of combination of the two, where the universe is split up into realms and players cannot see players in other realms but they can travel between these realms, like in World of Warcraft [...]
Read more: How to make a multi-player game – part 1

Create a Glowing, Flowing Lava River Using Bézier Curves and Shaders

Most of the time, using conventional graphic techniques is the right way to go. Sometimes, though, experimentation and creativity at the fundamental levels of an effect can be beneficial to the style of the game, making it stand out more. In this tutorial I’m going to show you how to create an animated 2D lava river using Bézier curves, custom textured geometry and vertex shaders. Note: Although this tutorial is written using AS3 and Flash, you should be able to use the same techniques and concepts in almost any game development environment.

Final Result Preview

Click the Plus sign to open more options: you can adjust the thickness and speed of the river, and drag the control points and position points around. No Flash? Check out the YouTube video instead:
The actual demo runs at a much higher framerate.

Setup

The demo implementation above uses AS3 and Flash with Starling Framework for GPU accelerated rendering and the Feathers library for UI elements. In our initial scene we are going to place a ground image and a foreground rock image. Later we are going to add a river, inserting it between those two layers.

Geometry

Rivers are formed by complex natural processes of interaction between a fluid mass and the ground beneath it. It would be impractical to do a physically correct simulation for a game. We just want go get the right visual representation, and to do so we are going to use a simplified model of a river. Modeling the river as a curve is one of the solutions we can use, enabling us to have a good control and achieve a meandering look. I chose to use quadratic Bézier curves to keep things simple. Bézier curves parametric curves often used in computer graphics; in quadratic Bézier curves, the curve passes through two specified points, and its shape is determined by the third point, which is usually called a control point.
Read more: Create a Glowing, Flowing Lava River Using Bézier Curves and Shaders

Monday, October 8, 2012

Use Any Sprite As a Stage3D Texture

Textures are usually simple bitmaps, but what if you wanted to use something more dynamic? How about a SWF you’ve created in Flash Professional? How about a Sprite or MovieClip you’ve created in code? Today’s article will show you how to do just that. First of all, there’s no magic Flash API that accepts a [...]

Read more: Use Any Sprite As a Stage3D Texture

Sunday, October 7, 2012

Implementing Tetris: Collision Detection

I’m sure it’s possible to create a Tetris game with a point-and-click gamedev tool, but I could never figure out how. Today, I’m more comfortable thinking at a higher level of abstraction, where the tetromino you see onscreen is only a representation of what’s going on in the underlying game. In this tutorial I’ll show you what I mean, by demonstrating how to handle collision detection in Tetris. Note: Although the code in this tutorial is written using AS3, you should be able to use the same techniques and concepts in almost any game development environment.

The Grid

A standard Tetris playing field has 16 rows and 10 columns. We can represent this in a multidimensional array, containing 16 sub-arrays of 10 elements:
Imagine the image on the left is a screenshot from the game – it’s how the game might look to the player, after a tetromino has landed but before another has been spawned. On the right is an array representation of the game’s current state. Let’s call it landed[], as it refers to all of the blocks that have landed. An element of 0 means that no block occupies that space; 1 means that a block has landed in that space. Now let’s spawn an O-tetromino in the centre at the top of the field:
tetromino.shape = [[1,1],
                   [1,1]];
tetromino.topLeft = {row: 0, col:4};
The shape property is another multidimensional array representation of the shape of this tetromino. topLeft gives the position of the top-left block of the tetromino: at the top row, and the fifth column in. We render everything. First, we draw the background – this is easy, it’s just a static grid image. Next, we draw every block from the landed[] array:
for (var row = 0; row < landed.length; row++) {
    for (var col = 0; col < landed[row].length; col++) {
        if (landed[row][col] != 0) {
            //draw block at position corresponding to row and col
            //remember, row gives y-position, col gives x-position
        }
     }
}
My block images are 20x20px, so to draw the blocks I could just insert a new block image at (col * 20, row * 20). The details don’t really matter. Next, we draw every block in the current tetromino:
for (var row = 0; row < tetromino.shape.length; row++) {
    for (var col = 0; col < tetromino.shape[row].length; col++) {
        if (tetromino.shape[row][col] != 0) {
            //draw block at position corresponding to
            //row + topLeft.row, and
            //col + topLeft.col
        }
     }
}
We can use the same drawing code here, but we need to offset the blocks by topLeft. Here’s the result:
Implementing Tetris: Collision Detection
Note that the new O-tetromino doesn’t appear in the landed[] array – that’s because, well, it hasn’t landed yet.

Falling

[...]

Read more: Implementing Tetris: Collision Detection

Saturday, October 6, 2012

Drawing API with Starling

Drawing APIThis week a very cool contribution was added to Starling by Robert Silverton, the Graphics API Extension! So what is it? From github: This extension adds Jon Pace's 'Fill' and 'Stroke' display objects, with support for adding arbitrary vertices that are then triangulated for rendering on the GPU. The aim is to reproduce Flash's graphics API as closely as possible via simplified lineTo, moveTo etc calls within Shape.graphics and Sprite.graphics. Once the basics have been reproduced, the API can be augmented with more powerful features. An ear-clipping algorithm is currently used for triangulating the simple polygons generated by the moveTo, lineTo methods. Supports both simple and non-simple (self-intersecting) polygons. For those of you who always felt that not having a drawing API was limiting, there you go. We are already thinking about some new APIs we could add to Flash Player and AIR to make this extension even more powerful. Graphics query, anyone? ;) Feel free to contribute and enhance it. Lee Thomason from our team has already sent some optimizations for curveTo. See you there! [...]

Read more: Drawing API with Starling