Wednesday, December 28, 2011

Use Vector Regions to Implement Field of View in a Flash Game

In this tutorial, you will learn how to cast a field of view of a turret guarding a specific location. When an enemy is within the turret's field of view, the turret will shoot at them. Vector math will be used to help in implementing this field of view.


Final Result Preview

Let's take a look at the final result we will be working towards. Click on the turret at the bottom of stage to begin the simulation.


Step 1: Field of View

I’m sure most readers have used cameras. Every camera has a view angle, defined by the type of lens attached. There are narrow and wide view angles. View angles constrain the field of view into a sector. From a top-down position, they look like the diagram below. If you take a picture, eveything within the grayed area will be captured.

Field of view: narrow and wide

The turret's field of view in our simulation is like that of a camera. If there's an enemy within its field of view, a guard will respond (sound an alarm, take aim, shoot, etc).


Step 2: Basic Concept

Mathematical conditions to determine item within FOV

The diagram above shows the field of view of turret. Usually the angle of view will be equal on both the left and the right. The radius will also be consistent throughout the sector. So to check whether an enemy is within a turret's field of view, these two mathematical conditions can be used:

  1. Distance between turret and enemy is less than radius.
  2. Angle from turret's line of sight to enemy is less than 30°.

Step 3: Define Field of View Using Vector

We shall use vector math to help us. In this case, the vectors in consideration are vLine2 and vLine3. We can:

  • Compare magnitudes of vLine2 and vLine3 to validate Condition 1 from Step 2.
  • Compare angle sandwiched between vLine2 and vLine3 to validate Condition 2 from Step 2.
Read more: Use Vector Regions to Implement Field of View in a Flash Game

Thursday, December 15, 2011

How to make a 2d platform game – part 2 collision detection

Hello and welcome back to my blog!

In this series of articles, I’m talking about the technology behind a platform game.

If you missed part 1 you can check it out here.

The language is actionscript 3.0, but the techniques are applicable to all languages.

In this particular article I’m going to talk about the physics, collision detection and AI aspects of the game.

2d platform game

The Game

There is a playable version at the bottom of the post, for those with Flash support in browser.

Class hierarchy

It makes sense at this point to talk about the class hierarchy I’ve used in the game, to represent everything which moves:

Class hierachy

Figure 1

Figure 1 shows the class hierarchy – at the very top sits MoveableObject, which is where all the generic collision detection and response gets done; I say generic because the player does specialised work to handle things like ladders etc.

Each level in the hierarchy represents separate functionality; for example, Character contains the AnimationController which handles playing the various different animations for each character, SimpleEnemy represents a certain class of enemy character which does no collision detection with the world, and obeys special position markers when it encounters them. The Diamond pickup is a simple object which has no AI, and just collides with the world, so it inherits from the base class, since that’s all the functionality it needs.

This may seem like a lot of extra complexity for such a simple game, but it really makes adding new enemy types very easy indeed, and simplifies the debugging process because there is so much code shared between each object.

If I had to give one piece of advice from 10 years of game development it would be this: avoid code duplication at all costs. It leads to slow development and bug city whereby you fix a bug in one location, and then forget to fix it in the other duplicated locations.

MoveableObject has certain properties which it requires be implemented by any class which inherits from it:

  • m_HasWorldCollision – whether full collision detection should be performed
  • m_ApplyGravity – whether gravity should be applied
  • m_ApplyFriction – whether the world collision should apply friction

That way, and child class can chose what elements of collision detection it wants enabled.

Consider the following snippet from the Skeleton character:

Read more: How to make a 2d platform game – part 2 collision detection

Friday, December 9, 2011

Create REAL explosions with Box2D

Look at the title… Create REAL explosions with Box2D… keyword: REAL.

This means we will make a Box2D explode into pieces using the basics of Slicing, splitting and cutting objects with Box2D. At the moment it’s just a prototype but it does not need that much optimization.

That’s what we’ll get:

Click the mouse to make the box explode.

Too fast? Get this slow motion example:

As you can see, this is a real explosion.

This is the source code, can you discover how was it possible?

Read more: Create REAL explosions with Box2D

Tuesday, December 6, 2011

Monitoring the Loading Process in Flash With the Loader Class

In AS3 projects, you often need to load external assets like images and other SWFs. While loading these assets you have to keep track of several events for successful execution of your application. You might have been using some of these events like ProgressEvent, COMPLETE event. This tutorial shows you how to get info about the assets you’re loading with Loader.load(), using its associated events, all in one place. So if you’re having difficulty loading such assets, or you have less time in hand to debug, take a look at this.

(Preview image courtesy of VisualPharm.)


Final Result Preview

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

This SWF loads an image, showing details about the loading process (progress, whether it’s complete, and more).

It won’t work embedded in this page (which shows you the responses in case of error) but it will work if you load the SWF directly.


Step 1:The need to load assets

Hey, if you are in a hurry, you can skip this step. But, if you are relaxed, with a cup of coffee in hand, have a read.

In the early days when I started learning Flash 5 and AS1, I used to have all objects on the stage at once, and made them visible/invisible as required. Eventually as I started developing apps, I became more familiar with Flash’s system. Wow, now I was able to use “linkage identifier” to load objects from library. Getting more advanced, I soon realised the need for external assets. But unfortunately, there was no such powerful architecture. Meanwhile, Flash was going through drastic changes. Now “AS2″ was capable of loading external assets. Finally, when it lined up in Adobe’s family, the new event-based architecture “Action Script 3.0″ was introduced. In AS3, the need for loading external assets is much better addressed than in AS2.

So, when working with Flash we have three ways to manage our assets:

  1. Put all required assets (MovieClips with instance names) on the stage and manipulate them as required.
  2. Put all required assets in the Library and access them using “Identifier” in library panel.
  3. Put all or some required assets outside Flash and load them dynamically.

The first method is not versatile. As the number of objects increases, the size of the SWF also increases (especially when there are lots of images). Imagine how much time it can take to load on user’s machine? Also, the performance of your application might degrade. But, still it can be handy enough for creating lightweight apps. (E.g. developing a simple game, in which player needs to find out key objects from the given image).

The second method is very much similar to the first one. Instead of having objects on the stage, now they are residing only in the library. Again, if there are lots of objects, then the issues with the SWF’s size and performance remain. But with this approach, you can easily create multiple instances of objects. Plus, the objects are much easier to handle than the first method. (E.g. games like “Tic Tac Toe”, “Tetris”, and “Snake” can be developed as they require fewer objects).

The third method (loading assets externally) is much more flexible than the first two. The power of this method is, without having a single object in the library you can still develop big games (e.g. “RPG” style games). As objects are loaded externally, they are loosely tied to your main SWF, so you do not have to go back to Flash every time you want to replace or edit your assets. One more advantage of this method is, it allows you to load and display objects on an “On Demand” basis. Meaning, you can load your objects only when they are required and unload them when you are completely done. (E.g. if your game has 10 levels, then you do not need to load all assets needed for all 10 levels. Instead, load and unload them level by level.) Thus, the overall performance of the application is improved.

Note: The above “On Demand” method may not be suitable in case where assets are loaded and unloaded frequently (e.g. in an image viewer app).

Okay, so now we can conclude that, of the three methods, the third one is more flexible. But, as the system gets more advanced, it becomes more complicated to manage. Similarly, if you decide to go with third method, you will need to handle assets as one separate operation. You may call it “Asset Management” which can be divided into two parts:

  • Handling assets manually (involves folder structures and operations like cut-copy-paste)
  • Handling assets programmatically (involves loading, displaying, and unloading in a program)

This tutorial covers the second part, so let’s look at that now.

As our program loads assets externally, it is now dependent on those assets. If any of our assets fail to load for some reason, then our entire application will be hampered. To avoid such failures, we really have to provide “Decision Making” power to our program.

Here’s one example. You have a coin-flipping game, where the coin is an externally loaded image. Now, if this image fails to load, then what next? This is the perfect point where your program will take some decision(s). It might load another image for the coin, stored as a proxy. It might load the stand-by coin if you have placed it in the Flash library. This can be a lightweight coin made up of vector graphics and strokes converted to fill to keep the size of the main SWF as small as possible. If you do not plan to have stand-by coin, then your program could warn the user about failure.

Of course, this was just one case. For a complete game, you will need to use a mature “Asset Management” system.

Read more: Monitoring the Loading Process in Flash With the Loader Class

Wednesday, November 23, 2011

AlternativaGUI - an easy way to create an integrated interface

A library for creating user interfaces AlternativaGUI has been published. Download it from the official website of AlternativaPlatform company in GUI section. The library is free and can easily be used, including in commercial projects. According to the license agreement you only need to specify in the project the page link alternativaplatform.com.

AlternativaGUI provides greater flexibility in terms of creating new components or modifications of existing interface, which is achieved by using only the core classes. The library offers a wide range of user interface elements such as buttons, containers, container line, scrollbar, tools for working with raster graphics and more.

AlternativaGUI Features

  • High performance
    Performance is achieved by the efficient work of all components of the interface in a single system. At the base classes implement only the required functional, hence the low consumption of resources.
  • Flexibility
    The library allows to create various graphics and can control their properties. Simplicity and clarity of API library allows you to extend all the classes are very easy to add and it is so functional that you need.
  • LOD elements
    AlternativaGUI allows you to develop an interface for different screen resolutions. This is accomplished by using different LODs for UI-elements (LOD - Level Of Details) and the correct scaling (for components with raster graphics). Each element has several LOD graphics states. When switching LOD may change the font size, icon size, can be hidden unimportant elements or, conversely, offers additional information. This logic is described by the developer. LOD switching is automatic. A special use of LOD is the development of interfaces for mobile devices with different screen resolutions.
  • The quickness of creating unique component
    Through the use of base classes, the creation and management component runs on a deeper level. Base classes do not contain any graphics, and determine only the logic of the components.
  • User friendly API
    Working with components AlternativaGUI is like working with the standard classes such as Sprite.

For rapid prototyping interface was developed the skinned library AlternativaGUI Default Theme, which contains the basic components. This library is available with source code.

Download AlternativaGUI
Read documentation
Open demo in a new window

Read more: AlternativaGUI - an easy way to create an integrated interface

Tuesday, November 15, 2011

How to Add Mouse Gesture Control to Your Flash Projects: Single-Stroke Gestures

I recently bought my first Bamboo, a Wacom tablet that recognises letters from shapes drawn with the stylus. It tickled memories of my first experience with gesture-controlled application: using mouse gestures, web browsers such as Maxthon (and later Opera) allowed users to quickly move back and forth through webpages in the history, switch between different tabs, and so on. I was facinated by its neat user interface, as it takes away traditional mouse clicks. Of course, sophisticated gesture-controlled devices such as the Kinect, iPad and iPhone are now available – but it all started with the good old PC. In this tutorial, you’ll learn how to develop a photo gallery that recognises singular mouse gestures.


Final Result Preview

Let's take a look at the final result we will be working towards. To pan the photo galley in the four main directions, click and drag the mouse in the relevant direction. To scale a photo, drag the mouse South-East to scale up and drag the mouse North-West to scale back to the default size.

(Note: this doesn’t snap to center the photo when panning; it’s sensitive to the length of the line that you draw.)


Step 1: Tutorial Flow

Here’s what you’ll learn in this tutorial, and the order in which you’ll learn it:

  • Vector interpretation of mouse gestures
  • Hard coded implementation of mouse gestures
  • Class to detect singular mouse gestures
  • Sample application (photo gallery) using mentioned class

Step 2: Gesture Detection: Vector Analysis

Image showing 8 main directions for mouse to detect.

It is important to understand the vector math involved in detecting mouse gestures. Having understood detection of a single direction, one can easily extend the understanding to apply to all eight directions.

The Flash presentation below shows steps of detecting a single mouse gesture to due right. To scroll through frames in the Flash presentation below, (mouse down – mouse move – mouse up) in any of the following directions:

  • Eastward to scroll frame forward
  • Westward to scroll frame backward
  • Northward to jump to last frame
  • Southward to jump to first frame
Read more: How to Add Mouse Gesture Control to Your Flash Projects: Single-Stroke Gestures

Friday, November 11, 2011

Effectively Organize Your Game’s Development With a Game Design Document

Have you ever dived right in to developing a game, but found yourself having to constantly change aspects of the design or the gameplay due to a lack of planning? You should consider using a game design document: a guiding vision of the game as a whole, pulling together ideas and plans for the design, development, and business sides of your game.


Introduction

To put it simply: we like to tell stories. Some true, some not so much. But the point is that we have been crafting tales for a very long time, and as time went by these tales began to evolve, becoming more complex, with richer details, with more and more fantastic backgrounds and appealing plots. Whole new worlds were born from thin air, hammered into shape in the anvils of the human brain.

And as the stories grew in complexity, so did the tools used in their making. Art diverged into several different categories, music became more elaborated and movies found their way into the world. Technological enhancements allowed sharing of information, spreading art all around the globe. New fantasy worlds were created each day. Worlds so rich made people began to desire becoming a part of them. A new concept was being brought to life.

Although video games were first just about getting the highest score possible when faced with a determined task, developers soon realized the endless possibilities laying ahead of them. Playing a video game is more than simply sitting through another story. For the first time one could have a say in how the tale told itself. Players could take hold of characters and live the hardships of the journey themselves, diving into that particular world and mastering it, making theirs the protagonist’s conquests and failures.

A game has the potential to bond player and story in a way never seen before. This connection can be established in a variety of ways. Be it the fantastic landscapes in which the story unravels, the soundtracks or the well-constructed personality of a particular character. It forces the player to thrive in order to see more of what he wants.

Unfortunately, since a game is composed of so many different elements, different experts from different areas are required in its creation, making the coordination of the development process a rather tricky job. In order to help developers do their job, a document known as a GDD, or Game Design Document, is often employed.

A GDD is a tool that helps merging the components of a game together. It registers the general ideas of every aspect of it, from graphics design to story line. In short it registers the game concept, creating the closer feeling of the finished product.

Although the writing of a GDD is not a vital part of the creation process, it is of major help to the team of developers, especially when in major projects, involving large amounts of personnel. Also, there is not only one way of writing a GDD. In fact, GDDs differ vastly among game development companies, but as a general rule, most games are built around these documents.

So without further ado, here is what you need to know about this important tool [...]

Read more: Effectively Organize Your Game’s Development With a Game Design Document

Wednesday, November 9, 2011

Create a QR Code Generator in Flash Using AS3

QR codes are everywhere these days: magazine advertisements, billboards, even TV commercials. Chances are you have a phone in your pocket that can read a QR code and decode the URL or message contained within. In this tutorial, you’ll learn how to create a SWF that can reverse the process: create a QR code from a URL or message. Read on!


Final Result Preview

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


Step 1: Brief Overview

Using pre-made graphic elements we’ll create good looking interface that will be powered by several ActionScript 3 classes.

The code will make good use of a QR Code Encoder class, created by Jean-Baptiste Pin.


Step 2: Flash Document Settings

Open Flash and create a 480 pixels wide, 480 pixels tall document. Set the Frame rate to 24fps.

Create a QR Code Generator in Flash Using AS3

Friday, November 4, 2011

Design Tactics – Select Single

The other day I was coding a particular UI implementation and realized that I had coded the same thing in multiple languages multiple times. I knew exactly how I was going to go about it and did what I usually do and, as usual, it worked just right. I started wondering how many examples like that exist, and that it would be good to occasionally document them, if not for my own sake, then for the sake of others.

These things aren’t necessarily so broad in scope that I’d call them design patterns. I might call them a design strategy, but that still has the connotation of being broad in scope, and could be confused with the strategy pattern. So I thought of naming them design tactics. Kind of like hand-to-hand combat with your code.

The first one, and the one that sparked my interest in the subject, I call the Select Single Tactic. I’m sure you’ve done this plenty of times yourself. It’s basically the functionality of a radio button, a list, a menu or other navigation. You have a number of items, of which only one can be selected. When the user selects one, it usually changes its state to show that it is selected, and the other associated items will change their state as needed to show that they are unselected.

The most common scenario is that the user will click on an item to select it, so we’ll go with that idea. A common first start is to code the item so that it responds to the click directly, changing its state to selected. See the following snippet, kept in pseudocode as it can apply to just about any language:

// constructor
Item() {
        this.addEventListener(click, this.onClick);
}

void onClick() {
        this.setSelected(true);
}

Here, the item responds to its own click by changing its visual state to show that it has been selected. In some cases, this is fine, but there’s probably a more elegant way. However, we’ll leave it like this for now [...]

Read more: Design Tactics – Select Single

Wednesday, November 2, 2011

Flash Game Dev Tip #14 – How to create a Flixel plugin

Tip #14 - How to create a Flixel plugin When Adam created Flixel 2.5 he added support for plugins. Probably due to my constant harassing him on GTalk about it, but he did it all the same! And lots of my Flixel Power Tools take advantage of them. But it's not always easy to know when you [...]

Flash Game Dev Tip #14 – How to create a Flixel plugin

21st Century Game Design - Part I

21st Century Game Design, by Chris Bateman and Richard Boon, 2005.

Part I - Games exist primarily to satisfy the needs of an audience

ch1 - Zen game design

Zen Buddhism can not be learned, it can only be experienced. There is no objective perspective on anything. Hence zen game design's tenets: game design reflects needs + there's no single method to design + there exist methods to game design. These methods are:

  • first principles: what you want to do -> game world abstraction -> design -> implementation
  • clone and tweak: most common method. existing design -> tweak -> implementation
  • meta-rules: goal = provoking debate. meta-rules -> design -> implementation
  • expressing technology: in teams without actual game designers. technology -> game implementation
  • Frankenstein: art or technical materials -> design -> implementation
  • story-driven: narrative -> design -> implementation

Participants in the game project: audience, publisher, producer, programmers, artists, marketing/PR, license holder. Example: saving for causal audience is vital; for hardcore audience, it should not break gameplay; for programmers, it's a technical detail; for producer, it's looking at how other games do it.

ch2 - Designing for the market

The commercial success for a medium clears the way for artistic expression, not the way around

A game design is successful when the target audience is satisfied. This justifies the need for an audience model. Existing models: simple distinction hardcore/casual, distinction by genre (but genres are too vague), EA's model, and ihobo's model.

Simple hardcore/casual distinction
hardcore casual
plays lots of games plays few games
game literate game illiterate
plays for the challenge plays to relax, kill time, and just for fun
segment can be polarized: many can buy the same title hard to polarize, diverse and disparate

EA's model:

EA's model take-away: do not ignore hardcores because they are the ones pushing a game to broader segments. Corollary: no TV ads are needed if the game is not made for casuals.

iHobo's model [...]

21st Century Game Design - Part I

Thursday, October 27, 2011

AS3 101: Events – Basix

For this chapter of AS3 101, we will be diving into the mechanics of the Flash event system. If you’ve been following along so far, you’ll have seen events in use, dating all the way back to the first episode of the series. The editor and I felt that it was time to write up something to be formally included in the curriculum, so if you’ve ever seen those lines of code about adding event listeners or dispatching events, and not quite caught on, then this is the tutorial for you.

There already exists an Activetuts+ tutorial on the basics of Events, so the focus of this tutorial will be on dispatching events from your own classes, including creating custom event types and objects.

To be successful with this tutorial, you should feel comfortable with writing and using your own classes in ActionScript 3, as well as feeling secure with using the existing events provided by Flash, such MouseEvent.CLICK or Event.ENTER_FRAME. We will be focusing primarily on dispatching custom events from custom classes.


Preview

We’ll spend a lot of time on the theory for this tutorial, but in the end we’ll build a simple slider control that dispatches its own events:


Step 1: Why Use Event Dispatching?

This example is actually a rather simple example of why you’d want to dispatch your own events. When you write your own classes, you are ideally keeping them in their own black boxes and encapsulated. But you still need to have the various objects interoperate in order to create a useful program.

The event model provided by ActionScript 3 is a rather good and convenient way to facilitate communication between your classes, while maintaining a separation of responsibilities in your classes. So if we write our own custom class, such as the ActiveSlider class showcases above, we have a need to enable other objects to be aware of when the slider changes its value. If the slider can dispatch its own change event, then other objects that need to know that information can easily subscribe and be notified.

Personally, I find the need to dispatch my own events in my classes so common that my class template sets up each new class with the boilerplate it needs to be able to do so. As you learn to keep objects discrete, you’ll turn to event dispatching as the most common technique to do so.


Step 2: How to Dispatch Your Own Events

I have good news: dispatching your own events is actually very simple. It is one of the core tenets of ActionScript 3, built in to the Flash Player, and as such there is only one thing you need to do in order to gain the ability to dispatch events. This one thing is:

Extend EventDispatcher

That’s it: when writing your class, use the line:

public class MyClass extends EventDispatcher {

Of course, you need to import EventDispatcher, which is in the flash.events package. You will most likely need other classes in the package, so it might be most convenient to simply import the package with a wildcard.

import flash.events.*;

Step 3: Dispatch

Now you’re set up to dispatch an event. All you need to do now is call a method provided by EventDispatcher named dispatchEvent. Easy to grasp, no? [...]

Read more: AS3 101: Events – Basix

Monday, October 24, 2011

Rusher 2 – Commands

Rusher 2 Component-Based Game Engine

Go to Rusher 2 project homepage

This tutorial will be a short and easy one, since it’s based on the Keybaord example in the previous tutorial.

The CommandManager System

Rusher 2 has a built-in command manager system, which is automatically added to the BasicEngine. What is a command? It’s basically an object with encapsulated actions. In this way, it’s very easy to customly build your own commands and have them executed through a central system, the command manager system.

For more information on commands, you may refer to my tutorials on ActiveTuts+: Thinking in Commands part 1 and part 2.

If you have read about the Thinking in Commands tutorials and are excited about the serial and parallel commands, then you’ll get even more excited to know that Rusher 2 has them! Rusher 2 has a fully integrated command manager system that can execute serial and parallel commands in addition to simple commands. It’s okay if you have no idea what a serial and parallel command are. I’ll cover those special type of composite commands in later tutorials.

First thing’s first. Let’s have a quick flashback on what we have done in the KeyController component class in the previous tutorial [...]

Read more: Rusher 2 – Commands

Rusher 2 – Getting Started

Rusher 2 Component-Based Game Engine

Go to Rusher 2 project homepage

In this tutorial I’ll show you how to put together two minimalistic games, or two very simple applications in particular, one with mouse control, and one with keyboard control.

Extending The Engine

First, you’ll need to extend either the Engine class or BasicEngine class. The Engine class is the most abstract game engine, without any systems added to it. The BasicEngine extends the Engine class and already has some basic systems added to it, including the Clock system, the Mouse system, and the Keyboard system (not all of the added systems are listed here).

You override the addSystem() method and add new systems here. The system manager is passed in as an argument for you to add systems to. Here we add two systems to the engine, which we will write later. The DisplayObjectUpdater is the system that updates every entity’s view with their position data, although we’ll pretty much create only one entity in this example. The EntityCreator system gives our game a “kick start” by creating an entity and adding several components to it.

Our document class looks like this. It passes a sprite to the engine constructor, where the sprite is intended to be the main container [...]

Read more: Rusher 2 – Getting Started

Rusher 2 – Introduction

Rusher Component-Based Game Engine

Go to Rusher 2 project homepage

Here I’ll give a very brief introduction to Rusher 2, my next version of my component-based game engine for ActionScript 3.0.

Component-Based Game Engine

First off, what is a component-based game engine? In a component-based game engine, everything, literally everything, from physical information to AI behavior are represented as individual component. The most elemental unit in a component-based game engine is an entity, say the hero character, an enemy, or a collectable object in the game world. Each entity can have multiple components attached to it, fulfilling the entity’s logical purpose in the game. For instance, a hero character controlled by a player in the game can have: a physical data component, which contains the current position of the character; a view component, which holds a reference to a display object representing the appearance of the character in the game; and a controller component, which listens to player input from the player (keyboard, mouse, etc.) and then updates the physical data component by altering its underlying coordinate data.

Component-Based Game Engine

Systems

Much like entities, the engine itself also contains multiple components with different responsibilities, which are known as systems. The most basic game engine generally consists of four systems: a clock system, which “ticks” every frame in order to keep the engine up and running (basically the clock invokes the main loop every frame); an input system, which listens for player input; an update system, which listens to the input system and update the game logic accordingly; and a rendering system, which draws the game onto the screen based on the current game state.

Dependency Injection

In generally, maintaining the intertwining references in a game engine is a daunting task. For instance, an engine needs to know what systems are added to it, an entity keeps track of its own components as well as needs to access components of other entities sometimes, and a command object needs to hold a reference to the game engine that its command manager belongs to. All this could result in tons of code dedicated to reference management. Making sure every single reference required is passed around correctly and removed as necessary is not easy. Hence, Rusher 2 makes use of SwiftSuspenders, a Dependency Injection framework mostly renowned for playing an important role in Robotlegs, one of the most popular MVC frameworks [...]

Read more: Rusher 2 – Introduction

Friday, October 21, 2011

Quick Tip: Understanding getDefinitionByName()

In this Quick Tip, you’ll learn how to construct a reference to a class from a String, and then create an instance of that class, using a built-in AS3 function called getDefinitionByName(). You’ll also learn the best methods for using this in different situations.


Why Is getDefinitionByName() Useful?

getDefinitionByName() is very useful if you need to make new instances of classes by using a String. For example, if you had seven different tiles – each represented by a class called Tile1, Tile2, etc – and you needed to create an instance of each, you would have to write the following code:

private function createTiles():void
{
 var tile1:Tile1 = new Tile1();
 var tile2:Tile2 = new Tile2();
 var tile3:Tile3 = new Tile3();
 var tile4:Tile4 = new Tile4();
 var tile5:Tile5 = new Tile5();
 var tile6:Tile6 = new Tile6();
 var tile7:Tile7 = new Tile7();
 stage.addChild( tile1 );
 stage.addChild( tile2 );
 stage.addChild( tile3 );
 // You get the idea, it is very lengthy!
}

getDefinitionByName() allows you to solve this problem!


How to Use It

Now, the above code was a little messy and we had to type many lines just to make a few different tiles. This is how we could achieve the same goal using getDefinitionByName():

private function createTiles():void
{
 for( var i:int = 1; i < 8; i++ )
 {

  var tileRef:Class = getDefinitionByName( "Tile" + i ) as Class;
  var tile:tileRef = new tileRef();
  stage.addChild( tile );

 }
}

In line 6, getDefinitionByName() returns a reference of the class called “Tile + the current value of i in the for-loop“. So, when i is equal to 1, getDefinitionByName("Tile" + i); returns a reference to the class Tile1. We then create the tile and add it to the stage.

However, when you run this code, it will not work! You’ll get a variable is undefined error message, in most cases, because “Tile1″ might not be enough information for Flash to find the class. Let’s look at some workarounds.


Make It Work

There are a few commonly-used methods to solve the problem of the variable is undefined error you’ll get when you run the above code, and I am going to teach you what they are. I would also like to give credit to Gert-Jan van der Well of Floorplanner Tech Blog for this blog post.

Here are some of the methods you can use [...]

Quick Tip: Understanding getDefinitionByName()

Develop a Flash game like Angry Birds using Box2D – Killing the pigs

Do you know why Angry Birds had such as a worldwide success? Because people love to kill pigs in videogames.

I got sick when I saw Babe movie and I want to kill pigs since then.

Today, you will learn how to do it thanks to the second part of the Angry Birds tutorial.

Before we start, let me explain how we are going to kill them. A pig dies when something, including the bird, the objects in the game, and even the ground, hits it too hard.

Various objects in the game also break when they hit something too hard.

You are already able to see when two objects collide thanks to tutorials like Create a Flash prototype of The Moops – Combos of Joy, but we’ve never seen how to determine the force of the collision.

You still have to create a custom contact listener class, but rather than using BeginContact function which just has an argument we can use to determine which objects collided, we will use PostSolve, which has another argument, a b2ContactImpulse variable.

With b2ContactImpulse we can know the amount of impulse Box2D has to give to bodies to avoid them from penetrating each other due to the collision. In other words, the collision force.

Once we know the strength of the collision, we can compare it with the maximum strength allowed before an object breaks (which can also be different according to the material, such as glass, wood, stone) and if the collision will break the object, we simply remove it from the Box2D world, and then we’ll show a cute animation.

This is what I made with this concept:

Throw the pigeon to the castle on the right to see how all blocks (and the pig) which are hit hard get destroyed.

In this prototype, world boundaries and the bird itself can’t be destroyed.

This is the Main class [...]

Read more: Develop a Flash game like Angry Birds using Box2D – Killing the pigs

Tuesday, October 18, 2011

Reuse your Flash games code (as much as you can!)

Let me guess something: when you are designing your latest game, you start with a working prototype, design a couple of levels, maybe add some cute graphics then… in most case you abandon the project.

Since it happens quite often to me, I tried to focus on what is making me drop a project.

And I found once I have an almost working game, I get bored when it’s time to add splash screen, buttons, music, level selection, third part APIs, and all that stuff which isn’t related to the game itself.

So I decided to build some kind of framework/template which will do the boring job for me, letting me focus on what’s really importat: making games.

Look at these level selection screens:

Level select reuse

I made them in a minute, just changing some variables in my template.

Let me explain the concept: this is the class of the level selection screen itself:

Read more: Reuse your Flash games code (as much as you can!)

Tuesday, October 11, 2011

Five Lies They Tell You in Software

The following are 5 things I wish someone had told me back in January of 2000.

  1. The User is the Most Important Thing
  2. If You Don’t Evolve, You’ll Die
  3. Using OOP, Design Patterns, Frameworks, and TDD with the Right IDE Will Solve All Your Problems
  4. You Can Code Something Right The First Time
  5. There is a Clearly Defined Career Path in Programming

1. The User is the Most Important Thing

Making money is the most important thing.

Anyone who says the user is the most important thing hasn’t been in enterprise software, is endeavoring to fight against bad software, doesn’t run a business, or is talking about Open Source.

If you want good software, yes, you should pay attention to the user. Doing informal user testing, engaging with real users/customers while developing the software should be done. Investing in design early, heavily, and constantly are great ways to lead to building software that has a great user experience that people want to use.

That doesn’t implicitly make software magically sell itself. For mid-size to larger companies, those using the software aren’t the ones who pay for it. Often they’ll never use it, nor see it. They’ll be looking for the right marketing messages, and/or validation that it solves key problems THEY are concerned about. They are hoping to solve what they perceive as important problems to their business, not those actually using the software in their day to day jobs for their business.

A lot of the most profitable software is the most tortuous to use. Case in point, SAP. Atrocious user experience. Yet, it sells extremely well (well, did, heh, read Blue Ocean Strategy). SAP can “run your entire business”. No other software product can make that claim with that much history to validate the claim.

This is important when you consider extremely large companies with a variety of different departments from HR to shipping, to finance, to IT. Even a modicum of perceived productivity enhancements across the board implies a significant amount of money saved. Remember, the 3 ways to make more money in a business:

  1. Raise your prices
  2. Increase your output
  3. Lower your overhead
Read more: Five Lies They Tell You in Software

How To Select Units in an AS3 Game

In this tutorial, we will draw a selection rectangle with the mouse (as seen in strategy games such as StarCraft and Command and Conquer), and we will also learn how to select units with the rectangle!


Final Result Preview

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

Click and drag with your mouse to draw a rectangle that will select any soldier that it touches.


Step 1: The Setup

If you are using Flash, create a new ActionScript 3.0 file with the size ’550 x 400′. However, if you are not using the Flash IDE and are using another such as FlashDevelop or Flash Builder, this tutorial contains the SWC files so you can use MovieClips from within your IDE of preference. If you are curious on how to import MovieClips with your IDE, check out the Beginner’s Guide to FlashDevelop and Beginner’s Guide to FDT!

I should also note that I have included the FLA file in case you do not wish to draw any of your own material.


Step 2: Creating the Document Class

Ok, now you may be a little confused if you haven’t really worked with classes before. If you wish to learn more about why classes are important in programming, check out this article by kirupa, or this guide to the document class.

Create a new ‘ActionScript 3.0 Class’ and give it the name ‘SelectionDemo’. When the file has been created, save it as ‘SelectionDemo.as’. You should save files all the time. I can not stress this enough but the amount of times I have forgot to save work that I have done and lost it all doesn’t bear thinking about. So please, do save the files!

If you are using an IDE that generates the code for you when you create the class, you should have most of the code below. However, you must still add the lines that I have highlighted:

Read more: How To Select Units in an AS3 Game

Wednesday, September 21, 2011

Introducing Starling

Starling Framework LogoI am excited to introduce today a new project we have been working on, called "Starling". So what is it ?

Starling is a 2D framework for game development developed in collaboration with the Austrian company Gamua (already behind the Sparrow-Framework on iOS), running on top of Stage3D (Molehill). It allows developers to leverage the power of the GPU without diving into the low-level details of the Stage3D APIs (available in Flash Player 11 and Adobe AIR 3). I am convinced that most of Flash developers will love this initiative, as most developers would like to leverage the GPU while reusing concepts like an event model, a display list, movieclips, sprites, etc.

Most of you, who had a look at the Stage3D APIs understand that this can be complex sometimes. So instead of writing 60 lines of code to draw a textured quad.

You will write the following :

// create a Texture object out of an embedded bitmap
var texture:Texture = Texture.fromBitmap ( new embeddedBitmap() );

// create an Image object our of the Texture
var image:Image = new Image(texture);

// set the properties
quad.pivotX = 50;
quad.pivotY = 50;
quad.x = 300;
quad.y = 150;
quad.rotation = Math.PI/4;

// display it
addChild(quad);

Quite nice hu ?

Of course, as a little obligatory test, find below a bunch of things (yes, sausages!) moving around :

Sausages

Click for demo.

Here is below another demo using Starling plugged with Box2D (for physics) :

Starling and Box2D

Click for demo.

Then, you have complete rendering of the your physics scene on the GPU.

Then of course particles! :

Starling Particles

Click for demo (press right key for starting the particles and change).

Below a more concret example including MovieClip (through spritesheet) :

Sausage Kong

Click for demo.

If you want to learn more about Starling, check the little book (Introducing Starling - 107 pages) I wrote about it, you can download it from the link below, it covers many concepts to get started with Starling :

Starling Book

click to download (Introducing Starling - rev 1.0).

Check the official Starling website to download it and share your content with the Starling community.

I hope you will like it!

Read more: Introducing Starling

Monday, September 19, 2011

Composing BitmapData Scenes

Since Flash 8, BitmapData has offered a wide range of possibilities to improve performance. Many Flash apps, particularly games, choose to simply display a single, huge BitmapData, render the entire game scene into it and, for the most part, eschew Stage‘s whole system of DisplayObject and DisplayObjectContainer. When you’re doing this or just generally using [...]

Read more: Composing BitmapData Scenes

Saturday, September 17, 2011

Learn HTML5 With This Simple Avoider Game Tutorial

In this tutorial (the first of a series), you’ll learn the basics of HTML5 game development with JavaScript and the <canvas> element. You don’t need to have any programming experience, or even any HTML experience (apart from this one article). Let’s get started!


Introduction

It would be difficult to have missed the “HTML5 vs Flash” articles that have sprung up all over the web, particularly since Steve Jobs’s Thoughts on Flash last year, and Microsoft’s announcement this week that Windows 8′s web browser won’t support Flash on tablets by default. I’m not going to get into that debate here; whatever your opinion, there’s no harm in learning HTML5. Even if you know Flash, it doesn’t hurt to have another tool in your kit.

This tutorial does not require you know know Flash, or to have had any experience of programming before. In fact, everything that you need to know before you get started is explained in this single article: Get Up to Speed With HTML. That’s it! If you can follow that, you can follow this.

I’m basing this series on my Flash tutorial series, which in turn was based on an even older Flash tutorial by a guy named FrozenHaddock (to whom I am very grateful for letting me use his ideas). This isn’t a direct port of either tutorial, however; I’ll be completely rewriting the code and the explanations to suit HTML5.

A couple of notes:

  • Cross-browser compatibility is a real and important issue in web development, but we’re going to be a little selfish and focus on making sure our game works in exactly one browser: Chrome. Rest assured, we will deal with other browsers (including mobile) in other Activetuts+ tutorials, but for the time being, we’ll stick with Chrome, so that we don’t have to split our focus.
  • Clean code is more important in HTML5 than in a lot of other platforms, because the underlying programming language (JavaScript) will let you get away with a lot. So, we’re going to make sure that you get in the habit of writing decent code… eventually. We’ll be a little messy at the start, just to get things rolling and avoid making you scroll through thousands of words on “best practices” before actually getting to do anything.

In this first part of the tutorial, we’ll just be setting everything up and putting in some very basic game mechanics. Future parts will add multiple spawning enemies, high scores, menu screens, multiple levels, and all that stuff.

Enough talk – let’s get started!


Setting Up

First thing to do is create a .html file. You can use a basic text editor for this, or spend a few hundred dollars on software specifically designed for HTML development; personally, I’d stick with free software for now. Here are three recommendations: TextEdit (for Mac), Notepad++ (for Windows), and Sublime Text 2 (for Windows, OS X, and Linux). Take your pick.

Create a new file, and enter the following:

<!DOCTYPE html>
<html>
 <head>
  <title>HTML5 Avoider Game</title>
 </head>
 <body>

 </body>
</html>

If you don’t understand what any of that does, read my basic guide to HTML.

Create a new folder on your hard drive called AvoiderGame, and save this HTML file inside it as game.html. If you load it right now, it’ll just show a blank white page (as you know), so put a paragraph of text in there just to make sure everything’s okay. I’ll add a link to this tutorial, but you could enter anything you like – your name and website, perhaps?

<!DOCTYPE html>
<html>
 <head>
  <title>HTML5 Avoider Game</title>
 </head>
 <body>
  <p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial" rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
 </body>
</html>

JavaScript

Okay, now, you will not be surprised to hear that we will soon be writing some JavaScript – remember, JavaScript lets web pages do things, and that’s exactly what we need for making games. We’ll put all our JavaScript in an external file, in order to keep things tidy, and put this file in a separate folder, to keep things tidier still.

So, create a new folder, called js inside your AvoiderGame folder. Then, create a new, empty text file, and save it as main.js inside this new AvoiderGame/js/ folder.

Alter your HTML to refer to this JS file:

<!DOCTYPE html>
<html>
 <head>
  <title>HTML5 Avoider Game</title>
  <script src="js/main.js"></script>
 </head>
 <body>
  <p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial" rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
 </body>
</html>

Note that I haven’t written src="http://active.tutsplus.com/...whatever.../js/main.js", or src="C:\AvoiderGame\js\main.js"; this way, we’re telling the HTML page, “look for a js folder in the same directory as you, and then use the main.js file that’s inside it.” It’s called a relative path.

If you want to test that this is working, put alert("Working!"); in your JS file, then load the HTML page. If you get a dialog box, everything’s okay.

<!DOCTYPE html>
<html>
 <head>
  <title>HTML5 Avoider Game</title>
  <script src="js/main.js"></script>
 </head>
 <body>
  <p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial" rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
 </body>
</html>

CSS

While we’re at it, let’s link an external CSS file as well; we can use it to make the text look nicer, and we might need to use CSS in the game later.

Create a new folder inside AvoiderGame called css, and then create a new, empty text file called style.css inside that. Modify your HTML like so:

<!DOCTYPE html>
<html>
 <head>
  <title>HTML5 Avoider Game</title>
  <script src="js/main.js"></script>
  <link rel="stylesheet" href="css/style.css" />
 </head>
 <body>
  <p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial" rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
 </body>
</html>

I’m going to modify my CSS file to match some styles we often use on demo pages here at Activetuts+; feel free to copy it, come up with your own, or leave yours blank:

body {
 background: #ffffff;
 text-align: center;
 padding: 20px;
 color: #575757;
 font: 14px/21px Arial,Helvetica,sans-serif;
}

a {
 color: #B93F14;
}

a:hover {
 text-decoration: none;
}

ol {
 width: 600px;
 text-align: left;
 margin: 15px auto
}

This tutorial isn’t about CSS, so if you don’t understand that, don’t worry about it. (If you’re curious, you can look up the meaning of those CSS attributes on W3Schools.com.)

Okay, that’s the dull setup out of the way. You can see how the page looks by clicking here, and you can download the entire source so far in a ZIP file here. Let’s create our avatar!


Get Your Head in the Game

We need an image that will represent our player’s character in this game. Use whatever you like – a photograph of your face, your Twitter avatar, a picture you’ve drawn – but make sure it has a transparent background, that it’s roughly circular, and that it’s about 30x30px.

The original tutorial on which this one is based used a skull. I’m not sure why, but I suspect it was an attempt to subvert games’ typical anti-skeleton stance; after all, under our skin, doesn’t every one of us have a skull?

I’m not one to break with tradition, so I’ll use a skull here too. You can download mine by right-clicking it, if you don’t want to make your own [...]

Read more: Learn HTML5 With This Simple Avoider Game Tutorial

Thursday, September 15, 2011

An Introduction to FlashPunk: The Basics

Learn the basics of how FlashPunk works – an amazing library to save you time and help you create the perfect game!


Final Result Preview

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

Use the arrow keys to move your character (the blue guy). The red/brown guy is an NPC; the shaded red area is a danger zone, and the green box is a button. You’ll learn how to create all this in this tutorial.


Step 1: What Is FlashPunk?

FlashPunk logo

FlashPunk is an ActionScript 3 library created for the development of Flash games. Basically, it does all the hard work for you and lets you focus entirely on developing your game, rather than on the engine behind it. The best part about it is that you don’t need Flash Pro to work with it: you can do everything with a free code editor like FlashDevelop. Not to mention it’s way faster when it comes to drawing things on screen, since it uses blitting!

This tutorial will go through all the basics of FlashPunk. After following it, you’ll be ready to make a simple game with this amazing library!


Step 2: Initializing the Engine

Begin by downloading the latest version of FlashPunk from the official site (this tutorial uses the version from August 30, 2011). Put the “net” folder, with all its contents, in your “src” folder.

FlashPunk has a class called Engine. This class is what starts everything in the library. Think of it as a Main class, but with special code to power up all the classes in FlashPunk. In order to use the Engine class, we will modify the Main class a little bit.

package
{
 import net.flashpunk.Engine;

 [Frame(factoryClass="Preloader")]
 public class Main extends Engine
 {

  public function Main():void
  {

  }

 }

}

Now, our class extends Engine. In Main‘s constructor, we need to make a call to the Engine constructor: this is what sets the important information about the game: width, height, framerate and whether the engine should run at a fixed framerate or not.

public function Main():void
{
 super(550, 400, 30, false);
}

There is a function that can (and must be) overridden from the Engine class: the init() function. It will run only once, and will initialize everything to get the game working.

override public function init():void
{
 trace("The game has started!");
}

I’m pretty sure everyone wants to put something on the screen and see this engine working! Because of that, the next few steps will cover the very basics of the elements of FlashPunk, adding depth as the tutorial goes on.


Step 3: Worlds and Entities

In FlashPunk, there are elements called Worlds and Entities. These are the main elements of the library, and you’ll work with them from the beginning to the very end of your game.

Worlds are pretty much like what is commonly known as a “screen”. Everything in your game will happen in a world: the main menu is a world that will give you access to the actual game world, where you will fight some enemies and die, which will lead you to the game over world, with your scores and statistics about how well you did. More about worlds will be explained later.

Entities are exactly what they seem to be; they live in a world and do something in it: a button is an entity; your character is an entity; enemies and bullets are entities. They are the things that give life to the game.

Given that, we will create the game world (there’s time to make the main menu world later, let’s jump to some action!) by extending FlashPunk’s World class:

package
{
 import net.flashpunk.World;

 public class GameWorld extends World
 {

  public function GameWorld()
  {

  }

 }

}

Now that you have created a world, you need to tell FlashPunk that you want this world to be the active one. Let’s do it in Main.as:

private var _gameWorld:GameWorld;

public function Main():void
{
 super(550, 400, 30, false);

 _gameWorld = new GameWorld();
}

override public function init():void
{
 trace("The game has started!");

 FP.world = _gameWorld;
}

And don’t forget to import net.flashpunk.FP!


Step 4: Adding an Entity, and Giving It an Image

Now that we have our world, we can make an entity by extending the Entity class and adding it to our game world [...]

Read more: An Introduction to FlashPunk: The Basics

Wednesday, September 14, 2011

MVC for games

Second thoughts on MVC (following a first article about the use of MVC by game developers). Let's assume that the user inputs are first caught by a controller, and a view is displayed to the user at the end. What are the communication possibilities in-between?

Vanilla MVC

As seen on Wikipedia, the theoretical 'vanilla' MVC refers to an architecture where the controller updates the model, then notifies the view, which in turn fetches the data to display from the model.

Application for games: the system is event-based: it is only awakened by the actions of the user. If the world has NPCs, they can not act independently of the user. It may be OK for turn-based games like Chess, but not so much for games with living worlds like Morrowind or Harvest Moon.

Web MVC

In web development, the "logic" is often split into multiple controllers. To determine which controller the user's action is targeted to, web frameworks such as ASP.NET or Spring use a front controller pattern. The front controller maps URLs to actions to execute (and which controllers to call). I'm not entirely sure, but compared to the vanilla MVC, it seems that the (front) controller is now giving the model to the view, instead of having the view fetching the model by itself. Therefore, the model to be displayed is carried from M to C, and from C to V, twice more data going around than in vanilla MVC (where it used to be moved only from M to V).

In games, the model can get quite large, and moving it around can get costly. It would not be so costly if only resulting differences to the model (instead of the whole model) were exchanged, but it depends on the modernity of the rendering. Alpha compositing makes it possible to render variations of the game state (ie the model) by layering image elements. Many games/game frameworks such as pygame still use bit blitting, which requires to erase and reprint the whole screen.

Game MVC

This nice article about MVC for games explains:

  • The controller handles the input and flow of the game logic. This is akin to the states your game can be in. My primary two controllers are main menu controller and an in-game controller. They are responsible for converting input into something the game world (model) can understand. Eg "Create unit x at base y".
  • The model handles all game logic. It has nothing to do with input, rendering or networking. It is a pure view into the game world. Designers need only worry about what’s in the model.
  • The view DOES know about the model. The [view] has read-only access to the model. This model can be anything. For my main menu it’s a list of UI controls the controller has built. For the in game view, it’s the game world. Rather than "reusing views in different controllers" what is more important is "having multiple views on a single controller". For example there might be a 2D and a 3D view of the game world.

What is still missing from the picture is the game loop. In games, the model is rendered by the view 60 times per second, and the inputs of the user are processed at the same frequency. As mentioned in the quotes above, some component, be it a controller or something else, still has to determine which view should be active at any given frame, and which controller it is associated with.

Read more: MVC for games

Understanding Date(): Making a Calendar in AS3

Today we’ll build a fully functional calendar widget using AS3. It’s not rocket science, just an excellent example of using the Date class, which can handle all the complexity of extracting times, dates, months and years. We are also going to use some Flash components, and make sure that this calendar is portable to Flash Builder, FlashDevelop, and so on.


Final Result Preview

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


Step 1: Brainstorming

Before starting to build the code, let’s take a look at what we’ll need:

  • A class file, Calendar.as,
  • A cell grid, to place dates,
  • Labels for day names,
  • Function to get current date, month and year,
  • Function to get previous months’ days,
  • Function to get future months’ days,
  • Something to address the leap year issue,
  • Interface to pick any month and year,
  • Portability (for Flash Builder, FlashDevelop, and other IDEs).

Step 2: Preparing the Calendar.as Class File

In this step we shall create a basic structure of our Calendar.as class file.

There are several ways of creating ActionScript class file, like using FDT, Flash Builder, FlashDevelop. And, of course, the “Higgs Boson” of this multimedia world: the one true Flash IDE. I am using Flash Professional. Create an ActionScript 3.0 class file. The following is the basic structure of Calendar.as to start with.

package  {

 import flash.display.Sprite;

 public class Calendar extends Sprite {

  //variables

  public function Calendar () {

   // constructor code
  }
 }
}

I am sure that you have saved this class file as Calendar.as in the new folder for this calendar app. If not please save it.

Step by step we shall modify this Calendar.as to make it fully functional.

In the next step we will create a few text fields to label the weekdays and dates.


Step 3: Setting Up Text Formats for Dates and Weekdays

In this step we will modify our class by declaring some variables and creating a new function setTextFormat( fontFace, fontSize ).

We will also passing some parameters to the constructor of the class.

Initially it will look like “Syntactic Sugar”, but as the tutorial progresses it will become “Syntactic Salt”. Sorry, but we want to keep this class compact so as to make it easily portable. The idea is to have only one class and that’s all.

So, keep a close watch on the constructor’s number of parameters and their order as we progress.

Back to modifying the document class…

package  {

 import flash.display.Sprite;
 import flash.text.TextFormat;

 public class Calendar extends Sprite {

  //variables
  private var dateCellFormat:TextFormat;
  private var dayLabelTxtFmt:TextFormat;

  public function Calendar( fontFace:String = "Arial", fontSize:int = 15 )
  {
   setTextFormat( fontFace, fontSize );
  }

  private function setTextFormat(whichFont:String, size:int):void {

   //date text format
   dateCellFormat = new TextFormat();
   dateCellFormat.font = whichFont;
   dateCellFormat.color = 0xFFFFFF;
   dateCellFormat.size = size;
   dateCellFormat.align = "center";

   //day label text format
   dayLabelTxtFmt = new TextFormat();
   dayLabelTxtFmt.font = "_sans";
   dayLabelTxtFmt.color = 0x000000;
   dayLabelTxtFmt.size = size - 3;
  }
 }
}

Observe all the parameters passed to the constructor: we have already assigned values to them. This is the way to create default values for parameters. If no parameters are specified when instantiating the class, these default values will be used instead. We will see this in coming steps.

Nothing visible yet. Wait for a few steps.


Step 4: Creating Cell Grid to Arrange Dates

The calendar is made up of rows and columns forming a grid.

But how many rows and columns?

It depends on the calendar type – Vertical or Horizontal.

Vertical view needs 7 (rows) x 6 (columns), while horizontal view needs 6 (rows) x 7 (columns) as shown[...]

Read more: Understanding Date(): Making a Calendar in AS3

Sunday, September 11, 2011

quickb2 – Box2D for Flash games

quickb2 – Box2D for Flash games

QuickB2 is a complete abstraction of Box2D, providing grouped hierarchies, extensible classes, and event-driven callbacks. The high-level interface enables developers to create physics simulations that are impractical to write using Box2D’s API alone. It takes care of things that you don’t want to, so that you can concentrate on your game.

Here are some examples of what it can do: http://quickb2.dougkoellmer.com/bin/qb2DemoReel.swf

Here is a place where you can ask questions: http://quickb2.dougkoellmer.com/forum

I’ve just gone and looked through the demo reel, and I have to say this is quite impressive. Obviously having a nicer to use, ActionScript 3 style syntax rather than the C++ syntax is a bonus, but what really makes this cool is the features that this library has, over and above the basics of Box2D.  Things like shape cutting, soft bodies; breakable joints etcetera.

You can find out more information, and download the source code from Google Code, at: http://code.google.com/p/quickb2/

quickb2 – Box2D for Flash games.

Friday, September 9, 2011

The Power of Finite State Machines: Concept and Creation

This two-part tutorial will cover creating a multi-state car using a finite state machine. We will start with Procedural FSM and progress into the State Pattern design pattern. Concept and creation will be our main focus during this first part; we will then proceed into application and extension during the second part.


Final Result Preview

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


What Is a Finite State Machine?

Wikipedia defines an FSM (Finite State Machine) as a mathematical abstraction sometimes used to design digital logic or computer programs. It is a behavior model composed of a finite number of states, transitions between those states, and actions, similar to a flow graph in which one can inspect the way logic runs when certain conditions are met.

It has finite internal memory; an input feature that reads symbols in a sequence, one at a time, without going backward; and an output feature, which may be in the form of a user interface, once the model is implemented. The operation of an FSM begins from one of the states (called a start state), goes through transitions (depending on the inputs) to different states, and can end in any of those available – however, only a certain set of states mark a successful flow of operation.

In my own words, an FSM is a device used by developers to create objects that have different behaviors determined by the current state they are in. Depending on the input, the object can react and/or transition to a different state.

One good example would be a 1970 HK VP70Z machine pistol, which has three firing modes: safety, single shot, and semi-automatic three-round burst. Depending on the current mode you have it set to (state), the result (output) is different when you pull the trigger (input).

Tools: When conceptualizing an idea (the multi-state object you’re trying to create), it’s best to use a State Transition Table to know what states and actions for those states you will need to add.


Step 1: Setup

It’s time to start a new project. With FlashDevelop, create a new AS3 project. For the name, put CarFSM. Click “Browse…” and save it to your desired location. Go into the Package slot and enter “com.activeTuts.fsm”. Make sure the “Create directory for project” checkbox is selected then click “OK” to finish.

Read more: The Power of Finite State Machines: Concept and Creation

Guide to Mochi Media services – Leaderboards

Once you are able to set up a game with Mochi Media and enable it for live update and connect with Mochi Services and use Link Tracking, it’s time to learn something which will tie players in front of their monitors until they show the world how much they rock: leaderboards.

Mochi Media offers to developers a great set of features, allowing them to create they own leaderboards with all kind of social options.

First things first, so let’s start from the game dashboard, with the Scores section yet to be activated. Click on ACTIVATE and you are ready to enter the world of leaderboards [...]

Read more: Guide to Mochi Media services – Leaderboards

Saturday, September 3, 2011

MochiLand: The Making of BioGems

BioGems: “The Making Of”

Introduction

BioGems is Mochi Media’s first in-house game, which can be found in the Mochi Media games catalog. It’s a puzzle battle game in which space pets fight to protect their planet. By matching gems on a board, the player gets his pet to attack the opponent, defend itself for a while, regenerate some health or energy, or fill up its Rage meter.

BioGems

Building a Team

My name is Dominique Ferland and I’m the game designer of BioGems. Before I joined Mochi, I worked on console games for about 4 years in Montreal. My title was never clear – something of a mix between an artist and a game designer. Growing tired of large-scale projects, I started making games in my spare time. The last game I made is the gamer trivia title, Geek Mind, which put me on Jameson’s radar for a Mochi in-house title. As soon as Jameson made an offer for me to start a development team and make fun games, I said goodbye to my old job!

CEO and co-founder of everything Mochi, Jameson Hsu is the best boss in the world. His vision for games is pretty simple – making awesome games he’d love to play. As we shared our love for games and discussed our game ideas, it was clear that we’d make a good creative team. As you’ll see in this post-mortem, Jameson’s input in the design and in the production really helped keep BioGems simple and super fun.

As Jameson and I were developing our puzzle game idea, we realized we would need a super programmer to join the team – that’s when Jameson found Nico Tuason, Master of Flash. Based in the Philippines, Nico has been making games and other Flash projects for years. He really impressed us with his little indie gems, Desert Moon and SolarMax, which really showcased his creative programming skills. Each time he’d add something to the game, it would be super polished, animated and tweaked to perfection. And he’s just an awesome dude.

Brian McBrearty, musical genius, joined in a bit later in development to add all the bleeps and bloops, the loud gem explosions and the awesome music. He did it all with such ease and awesomeness that it was kind of scary. Brian has designed sound and music for tons of films, games and other media – check out his blog for all that craziness.

Enough about us, let’s talk about the game! [...]

Read more: MochiLand: The Making of BioGems

Build an Isometric Map Editor With As3isolib

In this tutorial, I will introduce you to the concept of isometric content creation and the basics of designing with it, using the open source library As3isolib. We will use these skills to create a simple level editor, suitable for an isometric game.


Final Result Preview

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

The SWF has been squashed slightly to fit in the page; click here to see it full-size.


Step 1: What is Meant by “Isometric”

First, it’s important to know what we mean by isometric. Isometric is a Greek term which means having equal measurement: all measurements are to scale, no matter how far close or how far in the distance they are from the viewpoint. So in mathematics, isometric projection is a type of projection which preserves distance along objects.

Suppose you are in an isometric view; you will have a 3D view (e.g. when a camera takes a photo of you) where no matter you are, you will be shown at the same scale according to that camera. This is in contrast to a true perspective, where you will be reduced in size when you are far away from the camera.

Isometric and perspective view

As3isolib handles all the underlying math involved in creating your scenes and views, so don’t worry about the math!


Step 2: What Does Tile-Based Mean?

Tile based is a term used for any graphical content that uses tiles as a fundmental element. The concept itself is a bit old — it was used in older games for technical reasons — but this doesn’t mean that tile based games are now dead; these days 3D rendering is, but these 3D games can be tile based (and many are). This is where isometric games come in. Tiles are usually rectangular, but there are also square tiles, triangular tiles and even hexagonal tiles (as in some Civilization titles).


Step 3: Rectangular Maps vs. Isometric Maps

Rectangular tiles are the easiest of all to work with, though most of the time, when working in rectangle land, you use square tiles. You can use other sizes, of course, but square seems to be a favorite. The point of view for games with square tiles is usually top down or overhead. This just means that all your graphics must be drawn as though you are looking down on the object. Sometimes you can give your game a slightly angled view so that you are looking mostly down, but you can see some of the front or back.

Another point of view for square tiles is the “side-scroller” view, where you are looking at the world from its side. This was very popular among older action games like Super Mario Bros and the original 2D Duke Nukem. In a rectangular map, moving along the X-axis means moving east, and moving along the Y-axis means moving south. In an isometric tilemap, depending on its type, moving along the X-axis might mean moving southeast, and moving along the Y-axis might mean moving southwest. In isometric tiles we still use rectangular areas to contain the tiles; this is not going to change. What will change is how you will render them.

(Editor’s note: a great guide to different types of perspective can be found here.)


Step 4: Isometric Map Types

There are three types of isometric tilemaps: slide, staggered, and diamond. Each has its own set of quirks, its own methods of rendering, its own way of representing a tilemap, and its own method of navigating them. I will introduce them briefly in this step.

Slide Maps: The slide tilemap is probably the easiest to render, navigate, and interact with. Unfortunately, it has limited uses. It’s mainly used to scroll action games. Usually, a slide map has a horizontal X axis and a diagonal Y axis, although it is possible to have a vertical Y axis and a diagonal X axis. The tiles are blitted in horizontal rows top to bottom.

Staggered Maps: Staggered maps works perfectly in turn-based strategy games. It is also very useful in simulating a round world; it is best suited for maps that wrap around (move from one edge to the other). Each new row of the map is alternately shifted one-half of a tile left or right, which results in a zigzag pattern of tiles. The X axis is usually horizontal (increasing to the east), and the Y axis is southeast and southwest. Staggered maps are the most irregular of the three. The tiles are blitted in horizontal rows, top to bottom.

Diamond Maps: This type of map is very popular in real-time strategy games. These maps are the least offensive; slide maps have “tattered” tops and bottoms, and staggered maps have “tattered” edges, so diamond maps are the smoothest. In diamond maps, the only requirement is that both the X- and Y-axis are diagonal, so you can increase X-axis or Y-axis as fits you, like the X axis increasing to the southwest and the Y axis to the southeast [...]

Read more: Build an Isometric Map Editor With As3isolib:

Thursday, September 1, 2011

movieMonitor: an AS3 performance monitor with 10.1 features

Do you want to know how your latest Flash project is performing?

Here is movieMonitor, a little widget useful to display FPS, memory usage, stage size and number of children.

It’s based upon Hi-ReS-Stats by Mr.doob, but I added some new features to fit my needs, using some of the new System properties introduced by Flash Player 10.1

The usage is simple: just add

stage.addChild(new movieMonitor());

And you’re done. You can change stage with any DisplayObject if you want.

Look at this example:

Let’s see what do these figures mean:

FPS: current amount of frames per second (after the “/” you can see the amount of frames per second set in movie properties)

Minute average: the average amount of frames per second in the latest minute

ms per frame: the amount of milliseconds needed to draw the current frame

Direct: the amount of memory (in Megabytes) currently in use that has been directly allocated by Flash Player

Max direct: the maximum amount of memory allocated by the Flash Player so far

Total: the entire amount of memory (in Megabytes) used by the application, including the memory used by the container application, such as the web browser

Garbage: the amount of memory (Megabytes) that is allocated but not in use. This unused portion of allocated memory fluctuates as garbage collection takes place

Width: the width of the stage, in pixels. The width is calculated based on the bounds of the content of the stage (after the “/” you can see the stage width set in movie properties)

Height: the height of the stage, in pixels. The height is calculated based on the bounds of the content of the stage (after the “/” you can see the stage height set in movie properties)

Children: the number of DisplayObjects in the movie.

This is the script [...]

Read more: movieMonitor: an AS3 performance monitor with 10.1 features

Saturday, August 27, 2011

Create a terrain like the one in Tiny Wings with Flash and Box2D – adding textures

If you are following the series about the creation of a Tiny Wings-like terrain, you should know one of the most popular requests once I placed a car running on the hills was how to get rid of the debug draw graphics and use your own textures.

First, you need a seamless texture, or a texture without seam at least horizontally. I suggest you to pick a texture of the same length of the hills (640 pixels in this case) or a texture which width divides the lenght of the hills.

I used a rock texture taken from 40 watt.

Then, as soon as you place the polygons representing the hill slices, you also have to draw on a sprite the same shape you are giving your hill.

This will act as a mask for your seamless texture. And obviously remember to remove both the mask and the texture when they leave the screen to the left side.

This is what you will get:

Use UP and DOWN arrow keys to control the cart, and LEFT/RIGHT to balance it while in the air.

This is the fully commented source code: [...]

Read more: Create a terrain like the one in Tiny Wings with Flash and Box2D – adding textures