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