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.