logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
May 21, 2012
The Math and ActionScript of...
We see lines used in a lot of scenarios; curves are also used but perhaps not as frequently – but that doesn’t undermine their importance! In this tutorial we shall take a closer look at...
read more
May 20, 2012
Weekend Lecture: Understandi...
Interested in game design? This weekend, we feature a set of four interactive lectures: games that are about game design, by Pixelate. Play the Games Bub and Bob, two little 8-bit guys, will talk...
read more
top
Nov 14, 2011 Posted on Nov 14, 2011 in Hints and Tips | 10 comments

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

Step 3: Gesture Detection: Angle Alleviations

Implementing Step 2 will be easy. However, chances are 90% that users' gestures will fail. Diagram below shows commonly commited gestures (middle); they seldom comply with a rigid Vector pointing to due right (left). Thus, it's better to give alleviation for gesture inaccuracies (right).

Concept of angle alleviation for gesture detection.

For example, we can give an alleviation of 30° on both sides of the Vector pointing due right so that angle of any gesture's Vector that falls within that range will be accepted and interpreted as a gesture to due right.

Implementation of angle alleviation for gesture detection.

Step 4: Gesture Detection: Sample Implementation

Below is an implementation of gesture detection to due right. Press down on mouse, move mouse to the right, and release mouse within the Flash presentation below. Try to gesture a little off the absolute right to check out the implementation of alleviation.


Step 5: Variables

Lets look at the variables on our hard-coded implementation in Step 4. I’ve highlighted the important Vector2D variables. Take note of comments I’ve placed at the end of each variable.

private var t:TextField;
private var earlier:Vector2D		//store mouse location upon first click
private var latter:Vector2D		//store mouse location upon release
private var RIGHT:Vector2D = new Vector2D(1, 0);	//vector of absolute RIGHT

Step 6: Hard-Coded Implementation

I assume you already know the basics of putting a TextField into your project so I shall focus on the ActionScript implementation of mouse gesture. The implementation as indicated below is heavily commented. Important Vector calculations are highlighted as well. I encourage readers to examine these comments, especially those highlighted, to understand operations at different events at runtime.

(The Vector2D class is the same one I’ve used in previous tutorials, like this one.)

public function HardCoded()
{
	//Creating a textbox
	t = new TextField();
	t.selectable = false;
	t.width = 300;
	t.x = stage.stageWidth/2;
	t.y = stage.stageHeight - 30;
	addChild(t);

	//Start of gesture detection
	stage.addEventListener(MouseEvent.MOUSE_DOWN, start);
}

//Register mouse location upon mouse down
private function start(e:MouseEvent):void
{
	//Register mouse suppress location
	earlier = new Vector2D(e.localX, e.localY);

	//Start to draw line
	graphics.lineStyle(3);
	graphics.moveTo(earlier.x, earlier.y);

	//add mouse move and mouse release listeners
	stage.addEventListener(MouseEvent.MOUSE_MOVE, move);
	stage.addEventListener(MouseEvent.MOUSE_UP, up);
}

//Draw gesture upon mouse move
private function move(e:MouseEvent):void
{
	graphics.lineTo(e.localX, e.localY);
}

//Evaluate gesture upon mouse release
private function up(e:MouseEvent):void
{
	//Register mouse release location
	latter = new Vector2D(e.localX, e.localY);

	//Calculating vector of mouse gesture
	var result:Vector2D = latter.minus(earlier);

	//Calculating angle from absolute RIGHT to gesture vector.
	var deviation:Number = RIGHT.angleBetween(result);
	deviation = Math2.degreeOf(deviation);

	//Interpreting gesture with alleviation
	if (Math.abs(deviation) < 30) 		t.text = "RIGHT gesture detected";
	else					t.text = "";

	//Clear screen of previous drawing.
	graphics.clear();

	//remove mouse move and mouse up listeners
	stage.removeEventListener(MouseEvent.MOUSE_MOVE, move);
	stage.removeEventListener(MouseEvent.MOUSE_UP, up);
}

Step 7: Summary

For clarification purposes, here’s a summmary of the hard-coded implementation:

  1. Upon mouse down, begin gesture detection.
  2. On mouse move, update the latest location of mouse pointer.
  3. On mouse up, evaluate the whole gesture since (1).

Step 8: Gesture Angle Alleviations

Making an accurate gesture using a mouse is hard. It’s hard to make straight lines (East, South, West, North) but it’s even harder to make diagonal lines (South-East, South-West, North-West, North-East) because we have to estimate that extra 45°. So I have given diagonal lines more alleviations than straight lines. Notice the larger grayed angle for diagonal Vector compared to that of the straight Vector.

Alleviations for error on diagonals larger than straights.

Step 9: Gesture Sensitivity

 I'd to point out another issue – sensitive gestures. Sensitive gestures identifies gesture directions when mouse pointer makes the slightest shifts in location, even to adjacent pixels. Diagram below illustrate scenarios of sensitive gestures.

Sensitive mouse gestures.

If the user changes his mind after mouse press and mouse releases immediately, a gesture will still be detected if his pointer makes a slightest move to the adjacent pixels. We should allow users to undo gesture detection. In this tutorial, I’ve enforced a minimum magnitude the Vector of current gesture must exceed to be valid. I’ve included a diagram as below.

Minimum magnitude enforced on valid gesture.

Step 10: Class Variables

In order to detect singular mouse gestures I have implemented MGesture. Do download and examine this ActionScript file. I shall go through its class variables first, then the class methods.

Variable Datatype Purpose
mainBox DisplayObjectContainer Container from which gestures are detected
directions Vector. Vectors of standard directions
_deviationFromMains Number Angle alleviation allowed of gesture Vector from 4 main directions (0~3 in directions)
_deviationFromDiagonals Number Angle alleviation allowed of gesture Vector from 4 diagonal directions (4~7 in directions)
_minDist Number Minimum magnitude on current gesture Vector to be valid
_earlier Vector2D Location of first click
_latter Vector2D Continuous pointer location after first click

Below is the code implementation of class variables. I’ve allowed a deviation of 10° from main directions. For example, -10°-10° is considered due East, -80°-100° is considered due South, etc. I’ve also allowed a deviation of 30° from diagonal directions. So a Vector with orientation between 15°-75° will be considered due South-East, and so on. Also, the minimum magnitude to exceed is 10px.

private var mainBox:DisplayObjectContainer;
private var directions:Vector.<Vector2D> = new <Vector2D>[
	new Vector2D(1, 0), 	//East
	new Vector2D(0, 1),	//South
	new Vector2D(-1, 0),	//West
	new Vector2D(0, -1),	//North
	new Vector2D(1, 1),	//South - east
	new Vector2D(-1, 1),	//South - west
	new Vector2D( -1, -1),	//North - west
	new Vector2D(1, -1)	//North - east
];
private var diagonals:Boolean = false;

private var _deviationFromMains:Number = Math2.radianOf(10);
private var _deviationFromDiagonals:Number = Math2.radianOf(30);
private var _minDist:Number = 10;
private var _earlier:Vector2D;
private var _latter:Vector2D;

Step 11: Numbering Directions

You may have guessed it already from reference to code implementation of directions. For clarification, here are the main directions' integer representations.

Direction numbering.

Step 12: Class Methods & Property

Below are class methods for MGesture.

Methods Input Output Description
MGesture Container in which gestures are detected void Class initiation, setting container from which gestures are detected
start void void Variables for gesture detection (_earlier, _latter) initiates
update void Current gesture's Vector (without considering _minDist), Vector2D Updates _latter and returns current gesture Vector (_earlier to _latter)
validMagnitude void Current gesture's Vector (fulfills minimum magnitude of _minDist), Vector2D Checks if current gesture's magnitude is more than _minDist
evalDirections void Integer indicating direction, int Evaluates current gesture by comparing its Vector to those in directions

Step 13: Methods

The essential methods tabled in Step 12 are all documented here. Do read through the comments.

/**
 * Initiate variables
 * @param	container where mouse is detected from
 */
public function MGesture(container:DisplayObjectContainer) {
	//setting container from which mouse is moving
	mainBox = container;
}

/**
 * Method to register initial mouse location
 */
public function start ():void {
	var startMX:Number = mainBox.mouseX;
	var startMY:Number = mainBox.mouseY;
	_earlier = new Vector2D(startMX, startMY);	//pointer location, initially
	_latter = new Vector2D(startMX, startMY);	//pointer location, to be updated later
}

/**
 * Method to update mouse location
 * @return a Vector2D of current mouse location relative to that when start() is called;
 */
public function update ():Vector2D {
	_latter = new Vector2D(mainBox.mouseX, mainBox.mouseY);
	var vecUpdate:Vector2D = _latter.minus(_earlier);
	return vecUpdate;
}

/**
 * Method to validate a gesture.
 * @param	newLoc	Vector2D to new mouse location
 * @return	null if invalid gesture, a Vector2D if valid
 */
private function validMagnitude ():Vector2D {
	var gestureVector:Vector2D = update();
	var newMag:Number = gestureVector.getMagnitude();

	//if magnitude condition is not fulfilled, reset gestureVector to null
	if (newMag < _minDist)		gestureVector = null;
	return gestureVector;
}

/**
 * Method to evaluate gesture direction
 * @return Integer indicative of direction. Invalid gesture, -1.
 */
public function evalDirections():int {
	//Pessimistic search (initialise with unsuccessful search)
	var detectedDirection:int = -1;

	//validate magnitude condition
	var newDirection:Vector2D = validMagnitude();

	//if gesture exceed minimum magnitude
	if (newDirection != null) {

		//evaluation against all directions
		for (var i:int = 0; i < directions.length; i++)
		{
			var angle:Number = directions[i].angleBetween(newDirection);
			angle = Math.abs(angle);

			//check against main directions
			if ( i < 4 && angle < _deviationFromMains) {
				detectedDirection = i;
				break;
			}

			//check against diagonal directions
			else if (i > 3 && angle < _deviationFromDiagonals) {
				detectedDirection = i;
				break;
			}
		}

		//update mouse location for next evaluation
		_earlier = _latter;
	}

	//return detected direction
	return detectedDirection
}

Step 14: Photo Gallery

Now that the MGesture class is set, we shall proceed with an demo application (photo gallery) of it. I have included a source file here. Do download and follow along. First of all, get all images into the "lib" folder in your existing project. Images I’ve used here are courtesy of my wife and daughter.

Placing images into lib folder in project.

Step 15: Embed Images

Create a new Actionscript class and name it PhotoView. We shall use these images to construct our gallery.

  1. Generate embed code of images. They will be recognised as a generic Class object.
  2. Cast Class into Bitmap objects so that we can manipulate it further.
  3. Put all these Bitmap objects in a Vector array for easy selection later.
Generate embed code in PhotoView.
[Embed(source = '../lib/Week3.jpg')]
private var Week3:Class

[Embed(source = '../lib/Family.jpg')]
private var Family:Class

[Embed(source = '../lib/FatherDaughter.jpg')]
private var Daughter:Class

[Embed(source = '../lib/Jovial.jpg')]
private var Jovial:Class

[Embed(source = '../lib/NewBorn.jpg')]
private var NewBorn:Class;

[Embed(source = '../lib/Posing.jpg')]
private var Posing:Class

[Embed(source = '../lib/Smile.jpg')]
private var Smile:Class

[Embed(source = '../lib/Surrender.jpg')]
private var Surrender:Class

private var list:Vector.<Bitmap> = new <Bitmap> [
	new Week3 as Bitmap,
	new Family as Bitmap,
	new Daughter as Bitmap,
	new Jovial as Bitmap,
	new NewBorn as Bitmap,
	new Posing as Bitmap,
	new Smile as Bitmap,
	new Week3 as Bitmap,
	new Surrender as Bitmap
]

Step 16: Display List Management

It is important to clarify here the management of PhotoView's display list. I’ve included a Flash presentation here. To use it, make a gesture to right or left. For further details, refer to Step 2.


Step 17: Positioning Image

In the PhotoView's constructor, we initiate all necessary display objects and position them into place. Plus, we initiate MGesture and attach events listeners to start gesture detection. I’ve highlighted the event listeners. Their details are explained over the next two steps.

public function PhotoView()
{
	panel = new Sprite();			//Initate panel
	panel.x = stage.stageWidth / 2;		//Centering panel horizontally
	panel.y = stage.stageHeight / 2;	//Centering panel vertically
	addChild(panel);

	var currentBmp:int = 0;		//Current image selected for positioning
	var bmpGaps:Number = 60;	//Spacing between images
	var bmpOnX:int = 3;		//Number of images on horizontal axis
	var bmpOnY:int = 3;		//Number of images on vertical axis

	var bmp:Bitmap;			//Bitmap object to hold image
	var container:Sprite;	//Sprite container to hold bmp

	//scrolling through Y
	for (var j:int = -1*Math.floor(bmpOnY/2); j < Math.ceil(bmpOnY/2); j++)
	{
		//scrolling through X
		for (var i:int = -1*Math.floor(bmpOnX/2); i < Math.ceil(bmpOnX/2); i++)
		{
			bmp = list[currentBmp];
			bmp.x = -1 * bmp.width / 2;	//Bitmap centered horizontally in container
			bmp.y = -1 * bmp.height / 2;	//Bitmap centered vertically in container
			container = new Sprite();
			container.x = (bmp.width + bmpGaps )* i;	//Positioning container on x accordingly
			container.y = (bmp.height + bmpGaps )* j;	//Positioning container on y accordingly
			container.addChild(bmp);			//Add bitmap into container
			container.addEventListener(MouseEvent.MOUSE_DOWN, select);
			panel.addChild(container);		//Add container into panel
			currentBmp++				//Scroll to next bitmap
		}
	}

	gesture = new MGesture(stage);	//Initiate MGesture for gesture detection
	stage.addEventListener(MouseEvent.MOUSE_DOWN, start);
}

Step 18: Selecting Image to Scale

Line 99 highlighted is not related to detection of gesture, but merely to select image for scaling & placing it on top of all other images.

private function select(e:MouseEvent):void
{
	//Setting current image to scale &amp;
	//Placing it on top of all other images
	ImgSelected = e.currentTarget as Sprite;
	panel.swapChildrenAt(panel.numChildren - 1, panel.getChildIndex(ImgSelected));
}

Step 19: Start, End and Evaluate Mouse Gesture

First function below is executed upon mouse down. The second is executed upon mouse up. I’ve highlighted start() and evalGesture() as well as evant listeners.

private function start(e:MouseEvent):void
{
	//Start gesture detection &amp;
	//Listen for mouse up event
	gesture.start();
	stage.addEventListener(MouseEvent.MOUSE_UP, end);
}

private function end(e:MouseEvent):void
{
	//Prepare current gesture's magnitude for animation purpose
	//implement a maximum cap on gesture's magnitude
	gestureMag = gesture.update().getMagnitude() / 2;
	gestureMag = Math.min(gestureMag, maxMag);

	//Evaluate current gesture
	direction = gesture.evalGesture();

	//Once a valid gesture is detected, perform animation
	//No further gestures will be detected until animation ends
	if (direction > -1)	{
		stage.addEventListener(Event.ENTER_FRAME, move);
		stage.removeEventListener(MouseEvent.MOUSE_DOWN, start);
	}
}

Step 20: Animating the Panel and Images

Once the directions has been detected, animation will begin. Depending on the gesture made, the whole panel may move in four directions or one single image may enlarge or shrink.

private function move(e:Event):void
{
	var currentMag:Number 

	//Motion of panel translation
	if (direction < 4) {

		//Function of easing motion
		currentMag = gestureMag * Math.cos(currentAngle += 0.1);
		if (direction == 0) 	panel.x += currentMag;
		else if (direction == 1) panel.y += currentMag;
		else if (direction == 2) panel.x -= currentMag;
		else if (direction == 3) panel.y -= currentMag;
	}

	//Motion of image scaling
	else {

		//Setting a maximum cap on motion
		gestureMag = Math.min(0.30, gestureMag);

		//Function of easing motion
		currentMag = gestureMag * Math.cos(currentAngle += 0.1);

		//Conditions to scale up:
		//Gesture is to South-East &amp;
		//Image is not scaled up already
		if (direction == 4 && ImgSelected.scaleX < 1.30){
			ImgSelected.scaleX = ImgSelected.scaleY = -1 * currentMag + 1.30
		}

		//Conditions to scale down:
		//Gesture is to North-West &amp;
		//Image is scaled up
		else if (direction == 6 && ImgSelected.scaleX > 1){
			ImgSelected.scaleX = ImgSelected.scaleY = currentMag + 1;
		}
	}

	//If angle on easing function exceeds 90 degrees/ 0.5 Pi radian,
	//stop animation &amp; enable gesture detection
	if (currentAngle > Math.PI/2) {
		stage.removeEventListener(Event.ENTER_FRAME, move);
		stage.addEventListener(MouseEvent.MOUSE_DOWN, start);
		direction = -1;		//Reset direction
		currentAngle = 0;	//Reset angle
	}
}

Step 21: Publish PhotoView

Now all is set. You may finally publish your work by pressing Ctrl + Enter on FlashDevelop. Again. here's a piece of the final product.


Conclusion

This is not the end of it. In the next part, we shall look at detection of a gesture sequence, which will be even more interesting than this part (which really just showed the basics). Do drop comments and let me know if MGesture had been useful to you, as well as any bugs, if you encountered any. Finally, terima kasih for the time reading. I’m hoping to entertain my fellow readers in Part 2.



View full post on Activetuts+

Nov 11, 2011 Posted on Nov 11, 2011 in Hints and Tips | 10 comments

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.


Overview

A Game Design Document must teach everyone who reads it how the game that you’re talking about works. In order to do this, you need to explain not just the mechanics, but also how the game’s objects (characters, enemies, puzzles, weapons, environment, and so on) interact with each other, what your game is about, and how it looks. In a GDD, these points are discussed in some general sections.

Marketing

Marketing is a big section subdivided in many subsections that explain the major commercial aspects of the game, like public target, deadlines, competitors and selling points. This section is very helpful for business, since it shows what your game has in advantage over others and how it meets the consumer demand. In others words, it shows the game’s appeal.

High Concept

Before you start to tell the reader how your game works, you must clarify the core concept of your game, i.e., you must talk about the major aspects of your game in a very short way, so that the reader can anticipate what will be said in the GDD and pay attention to what is important to the game. For this, there is the High Concept section, which explains all of it, so that the reader won’t have to read many pages of the document just to know what your game is about.

For example: if you tell the reader that your project is a futuristic space shooter game, he will be able to imagine what kind of weapons, movements, enemies and others things will be used in the game.

Gameplay

This section is one of the most important in the GDD, because it explains how to control the objects in the game and how to make them interact with the other parts. Also, it explains how the player will execute the possible moves. Moreover, it’s interesting to comment the way that the game flows and what happens during the course of the game.

First Minutes

This is a subsection of the Gameplay section, and it exposes what the player will see in the game when it has just finished loading. It exposes the actions and reactions between the game and the players during this interval, helping understand the game’s progress throughout the gameplay and give a better idea of how to play it. It’s also an important subsection, since it will determine whether or not the game is fun.

Gameflow

This is a more detailed subsection of the Gameplay than the First Minutes. It describes all the options that the player can choose while he is playing. It’s a kind of flowchart that shows which reaction each option has, giving a picture of the game as a whole. Generally it shows a flow of screens (e.g. from the “Main menu” screen it goes to the “Select level” screen), but you can also put actions and consequences in it (e.g. if the player chooses the “Mage” character, all the backgrounds will have a “magical” feeling). It literally explains the way that the game flows, as the name suggests.

Victory Conditions

You also need to teach the reader in the Victory Conditions subsection, what must be done to win, when the player loses and under which conditions this happens. In other words, this section explains the goals of the game.

Number of Players

It’s important to specify how many people can play, because this implies the type of multiplayer – where applicable – that the game will support; for example: split-screen, LAN connections, Internet connections. Note: this section has influence over the Victory Conditions, since the players will need to do different things to win in a competition than in a cooperative game.

Art

Once you explained how to play your game, it’s import to show how your game will look like and which kind of art is behind it, since it’ll influence how the elements of your game’s universe will coexist, mixing the emotions of who is playing. This is a crucial point in the game’s marketing, because it shows the appearance of the game and the feelings it will pass to the player.

Technical Aspects

Another section that must be put in a GDD is the Technical aspects, since it defines the physical game requirements needed to play and specifies on which platforms the game will be developed, which engines will be used, and more. This affects the Marketing, as the kind of hardware used affects both the fanbase and the public target, i.e., the people who consume the game.

Is There a Formula?

All things said, you need to keep in mind that even if some general subsections are common between the GDDs, there is no static form to make this kind of document, and no such thing as a perfect formula. Every game designer has his own way to do this and you must discover yours. This is a hard job, but in this article we’ll give some tips explaining how to create each subsection of the GDD – however, it’s up to you to decide which of them are necessary to design your game.

Always be clear and concise in your text and use a lot of images, because they give the reader a faster and more real view about the game’s final result and they also ease the explanation about puzzles (if your game has them) and how characters, environment, monsters, screens, weapons and other objects from the game will work.

Moreover, you can also find new topics to add in your GDD, as long as it’s necessary to the understanding of the game’s core. Some things that deserve attention are the innovations and the particularities of your game. For example, if your game project brings up a new way of playing, or a specific graphic concept or if it’s focused in music (like a music game), you should discuss it in the document, to convince everyone why this innovation is a good idea.


Guidelines

A good way to start your Game Design Document is with the Marketing section, because it will be the section that your investor or client is interested in, thus allowing them to gain interest in your game faster. In indie game development, it is not a common section due to the common lack of investors, however, if you think in other projects not related to commercial purposes, such as a free game on App Store of Apple to help a charity institution, it’s important to keep track of plans related to the marketing aspect, since it will be really important to have a publishing plan.

After this, it’s important to put the High Concept, so the reader immediately will understand the core of the game and pay attention in the major aspects. You will figure out that in GDDs it’s common to always start with a basic and summarized definition of the game, and go on to present every detail step-by-step.

In the next section you should write about the Gameplay, which should include, as sub-sections, the First Minutes, the Game Flow, the Victory Conditions and Number of Players.

After that, you need to show how your game will look, so talk about the Art, using as many images as you can. In the end, you can talk about the Specific Sections, which should bring topics that explain: the innovations, the aspects that not necessarily all games have, like story, artificial intelligence, characters and others particulars things.

All the things said above are represented in the flowchart bellow, but it’s just a general schema and you can (and should) adapt to your game. Remember: there isn’t a perfect formula. Now that you have a kind of skeleton of the GDD, you will find in the Composition topic of this tutorial a more detailed explanation about what which section of a GDD holds.

Guidelines Flowchart

Composition

Although there isn’t such a thing as a perfect formula for composing your GDD sections, it’s important for you to include some crucial topics in it, as well as avoid some major mistakes. This section teaches you how to detail the sections presented in the Overview topic, while showing examples of how it’s done and some common mistakes.

The Marketing Section

There is no correct way of dealing with this subject, since your objectives for it will depend on your game. It’s also not really needed; you can either concatenate it all in a major subsection or spread it across the document, as some of the topics discussed here have much in common with others elsewhere. Despite the way you choose to do it, some topics should always be addressed:

Target Audience

Who will play it? This is no ordinary section, so don’t settle for a simple “for children” description, for example. There are endless ways to “classify” gamers, and you must explore this. Comment on how it will appeal to each category and try not to leave anyone out; they might share little in common with your product, but they still share something.

Right:

Turret Defense will appeal to male gamers of ages 15 – 25 who typically play FPS and RTS PC titles. In particular, fans of Sci-Fi themed games, movies, and books will be immediately attracted to Turret Defense’s space adventure setting and theme.
Turret Defense will have an ESRB rating of T (Teen) for ESRB Content Descriptor of Violence, suitable for ages 13 or older. To conform to the wishes of the publisher, Turret Defense will not use blood or any other content that would lead to further ESRB Content Descriptors related to violence.

Wrong:

Turret Defense will appeal to a large audience. Based on the experience of similar games, it should be a huge financial success in the video games market. We plan to advertise it heavily with ads on games-related websites with huge traffic.

(“A large audience” isn’t a valid fanbase, and it doesn’t explain why they would enjoy it. No mention of the ERSB rating or whether the game has any age-restricted material.)

Another good example:

OrBlitz is expected to receive an ESRB rating of Everyone. The main target market will be puzzle games fans, but the game’s many original aspects will attract a wider audience, including people that prefer to buy action-based games. Real time strategy games fans could also be interested in the game for its tweakability and other similarities with RTS games. Because of the lack of graphic violence and the intuitive interfaces, this game can target women as well as men. The game is relatively cute and colorful, and is expected to appeal to both American and Japanese audiences due to the content in it.

Notice all the classifications in the example: gender, age, nationality and genre. Keep in mind that many more categories may arise depending on your game. Predictions on the ESRB rating are also welcomed, therefore some restrictions regarding violence, sexual content and language should be addressed if needed.

Platform

Extremely straight-forward section. Just enumerate the platforms that your game is being designed for. An estimate of the system requirements are also a good call. If needed, you can comment on porting the game and the difficulties involved.

Competitors

This is a key subsection of your document. In here you must compare your game to others already developed. It is important to give a small description of the game being compared to, and point the similarities between both. This is an excellent opportunity to expand the comparisons that were already made across the GDD and give the reader a better picture of what the game will actually be.

At the end summarise your product’s strong points and convince the reader why would your product sell despite its competitors. This is the trickiest part, because you must pick good opponents, otherwise the reader just won’t know what you are talking about, and still keep your game’s image shining; therefore a good writing is crucial. Your ‘adversaries’ also help on the notion of how big your market can be.

Milestone Schedule

The Milestone Schedule subsection is where you must define each necessary steps in order to develop the game, which is basically a timeline of the intended completion of phases of your game. Through that, not only you, but also the investors, can have a very rough estimate of the interval of time needed to complete the project.

Other Subsections

You may choose to add some heavy market-related topics such as Costs Overview, that can comprehend equipment costs, people costs, additional costs and expected profit.

Future Plans

Sometimes there are so many ideas to complement a game that some of it must be put aside in order to meet the tight schedule of development. This section is specifically made to store those ideas, so that you can work on it later depending on how things work out. DLCs, possible sequels, minor improvements to gameplay, graphics and so on, all comes in here. You can also gather some ideas of what to do with the game once it is finished.

Example:

  • Add some side quests.
  • Enable the character to jump.
  • Make a movie telling your story as a developer.

The Introduction Section

The introduction section should provide the reader with a basic overview of the game itself, first with a light approach with the High Concept subsection and then with a broader one within the Summary subsection. You can also highlight the more innovative aspects of your game in a Key Features subsection.

High Concept

A one paragraph description of what your game is about. This should sound like the summary of a summary. Avoid any technical aspects, graphic or sound designs, complex gameplay features, or marketing details that aren’t strictly required (for example, if you’re making a rhythm game you should mention what kind of music style you will be using, whereas if your game is a puzzle you can just forget about music for now; it’s better to describe what type of puzzle the player will have to solve instead). The idea is to describe your game in the most non-technical and shortest way. A good tip is to use well-known games as examples for comparison, such as “X is a three-dimensional racing game with power-ups like Mario Kart”.

Right:

Scavenger Hunt is a three-dimensional arcade-style game where players race to collect items from a list before their opponents do.

Wrong:

Scavenger Hunt is a three-dimensional arcade game with puzzle elements set in a fictional neighborhood in the 50′s with cartoony graphics and music, where the player races to collect various home-related items from a given list in each stage, while using gags as powerups, before his opponents, which can be either CPU-controlled when in singleplayer mode or human-controlled players in multiplayer mode.

(Keep it short and simple)

Summary Overview

A more detailed description of your game, with less restrictions than the High Concept subsection. Start with the core aspects of the gameplay, describing what role the player will take, what’s his goal, what he will have to do in order to accomplish it, what will hold him back and why the game will be entertaining.

Next, do a quick introduction to the game’s setting and a brief description of the history (if any). It’s always nice to use an image instead of describing what the graphics will look like, so if you don’t have any sketches or conceptual art you should just paste pictures with similar art to what you will be using (that includes screenshots of other games as well!).

Key Features

The best way to compose this is using short topics (i.e. bullet lists) instead of long paragraphs. Basically you should tell the reader right away about all of the creative ideas you had which you thought would make your game a great game.

Right:

– Simple yet powerful physics that provides surprising results from a set of simple rules.
– Amazing Hatched and Cel-Shaded graphics.
– Never seen before paint system where color spreads out to the world as the gameplay picks up speed to a frantic pace.
– Powerful land crafting abilities that allow you to build complex paths the orbs can take, like tunnels and bridges.
– Various game modes and scenarios to choose from, each of which feels like a totally different game, favoring action or reflection.

Wrong:

The game will have simple yet powerful physics that provides surprising results from a set of simple rules, while using amazing Hatched and Cel-Shaded graphics and a never seen before paint system where color spreads out to the world as the gameplay picks up speed to a frantic pace, when players build complex paths by using powerful land crafting abilities which the orbs can take, in various game modes and scenarios.

(Too many ideas at once makes the reader lose the train of thought.)

Third-Party Software Used

A little explanation of the programming languages, libraries and software you will be using to create your game, as well as the programs you will use to adjust your graphics and sound engines and any other engines your game may need (like a networking one for multiplayer games).

If you’re under some heavy software/hardware restrictions, you should specify that in here (i.e. if you’re making a game for Apple devices, you have to tell you’ll be using iOS-compatible technology). Also if your game is aimed at PCs and you have an idea what the minimum requirements will be you should note them here. Although the non-programming people of the project probably won’t understand what the heck a “NVIDIA Cg 1.2.1” is, they’ll have to know it by name since that’s what the game will run on.

The Gameplay Section

This section is designed to describe how the game will effectively work, describing the game’s objective as well as its elements (menus, victory conditions, enemies, powerups, stages, …), and the interaction between each one of these elements with the player. If you feel like one subsection, such as “Enemies”, has too much content to be just a subsection you may promote it to a section of its own.

First Minute

It’s interesting for you to describe what the player’s reaction is going to be like as soon as the game loads, such as describing whether he can start playing right away or if he can navigate through menus to change some options beforehand, whether the player will have to learn the controls by trial and error or a tutorial will be presented to him, whether all stages will be available at the get-go or if he will have to unlock them in progression, and so on. Given you have already planned some stages ahead, you could narrate a short run of the player clearing a stage, describing the enemies and/or puzzles he had to go through in said stage.

Right:

After the title screen the player is presented with a list of games he can join and an option to create a new one. After selecting the option to create a new game a list of predefined levels appears on the right of the screen. (…) After the settings are adjusted three other players join and the game begins. A timer counts down from five while the players get ready, using the small amount of money they start with to place a few blocks. As a simple beat plays in the background, the board rotates around the middle of the screen, revealing the layout of the level. (…) The player’s goals are on each corner of the board. (…) As soon as the count down reaches zero, ‘Go!’ is displayed in the middle of the screen and the orbs start falling from the cloud, creating havoc on their path. (…) The player quickly places a stone corner block on the edge of the level and the orb bounces off it, only to end up in the player’s goal followed by a familiar cashier sound. The player’s score and cash are updated to 200, and he starts going through the blocks he can now place (…).

Wrong:

The game begins with the players facing each other in opposite corners. Player 1 decides to use all his money from the get-go and wins the game by using well-placed stone blocks to earn points.

(Although being essentially how the game will run, it needs more details.)

Gameflow

A nice complement to the “First minute” would be the “Game Flow”, which is usually represented as a flowchart. In contrast to the previous subsection, this one won’t focus on the first impression but rather give an overview of the whole picture, showing step-by-step which actions the player can take from the moment the game is loaded to when the player hits the “exit button” – i.e., ends his gaming session – including the gameplay itself in a somewhat high concept.

Right:

Good Gameflow Chart

(Example from Drexel Game Design’s Scavenger Hunt GDD.)

Wrong:

Bad Gameflow Chart

(Nothing THIS simple. Include, at least, all the screens that the player will run through!)

Victory Conditions

Here you state what is required for the player to clear a stage, win a match, or advance another level, whether your game is a puzzle, where the player advances to the next level when all pieces are combined in a certain way, or a sidescrolling shooter where the player advances a stage when he defeats the boss at the end, or whatever. Obviously, this depends entirely on what kind of game you’re designing.

Example:

In Space Invaders, the player advances to a new wave each time he destroys all enemies from the current wave. Since the waves are endless, the game will keep going until the player runs out of lives.

Graphics

You can’t really provide the reader with screenshots or video footage of something you may haven’t even designed yet, so in this subsection you should simply describe how do you plan to handle your graphical engine and maybe show some sketches of your game or a few drawings in the art style you intend to use. Planning the game HUD from the beginning will save you a lot of time later on, for example.

HUDs

The head-up-display is the in-game interface the player will have when playing the game. Rather than in-game menus like settings or inventory screens, this refers specifically to the floating windows and bars which don’t normally interact with the game and serve a information-only purpose. This includes health bars, mini-maps, time counters, equipped items and their amounts, money and etc. Although the size of the HUD will vary according to the game type (MMORPGs and RTSs will have big HUDs while sidescrollers and puzzles will have very small ones) keep in mind that a HUD shouldn’t occupy too much of the screen.

Example:

HUD Example

Sounds

On the other hand, one cannot sketch sounds, so you’ll just have to detail your sound engine here, and maybe the style of songs your game will use. Although for most games you will simply state that there will be different background music for different situations, it goes without saying that this subsection is most important for a rhythm game.

Controls

Stating which buttons/keys do what can be troublesome in the case where a single button does more than one action (i.e. The ‘A’ button in any 3D Zelda). Start by putting a simple picture of a controller or a keyboard with each button highlighted with their function in a more general sense. After that, if your game has advanced combos or something similar to that, explain them carefully, stating under which conditions each combo is “activated”.

Example:

Controls Example in a Xbox Game

(Image from CrunchTime Games Inc’s Shred Nedbula document.)

Game-Specific Subsections

Puzzles could have a “Pieces” subsection, sidescrollers will probably have a “Level Design” one, space shooters may have “Enemies” and so on. As the title in bold above says, each game will have their own specific subsections, and since we can’t compose a subsection for all the possible ones that one GDD can have, we will provide you with the three bold subsections presented here as examples.

Pieces

Suppose we have a puzzle game, where the player rotates different pieces in order to create a line of matching pieces to gain points. This would be a nice subsection to show some sketches of the many different types of pieces, as well as explaining their rotation pattern, stating their points value, and maybe describe their positioning placement. Pictures are welcome as always!

Example:

Diagram of the design, length and rotating pattern of the pieces in Tetris

(Image from Colin Fahey’s Tetris article.)

Level Design

Now let’s pretend we have a typical 2D platformer. One of the core elements of the game is the stages the player has to go through. It’s important that each stage feels unique so the player won’t feel like he’s just repeating the same thing over and over again. On the other hand, the player should still be familiar with the flow of the stage, i.e. if there’s always a checkpoint somewhere halfway through it, or some collectible items along the way.

What are the different types of enemies, terrains, doodads and power ups and do they allow the level designers to come with many different stages? You could present some beta stage diagrams to illustrate how will they be carried out.

Example:

A stage design from a platformer game. A detailed 1-2 paragraphs explaining  the landmarks should follow the image.

(Map from Super Metroid; image from jansenprice.com.)

Enemies

It’s very popular for space shooters to have many kinds of enemies, each one with different attacks and movement patterns, as well as different values for health, speed and targetable area. As such, it’s no surprise you would need an extra section to present all the game’s foes and their stats. Also, you could state some of their more obscure behaviour like shooting an extra beam when their health is low and so on.

Example:

An enemy attack pattern as seen in R.I.P Rocket

(Image from CrunchTime Games Inc’s Shred Nedbula document.)

Plot

Many games are set in fictional worlds, each with their own geography, history and characters, in which the player will undoubtedly play a large role as the protagonist. If your game has a particularly interesting setting, it would be interesting to include a little insight on the game’s storyboard, describing the protagonist’s main events during his adventures and details about the lore.

Characters

Lots of games aren’t made of enemies alone. There may be a protagonist and allies to help him overcome his foes. For example, even a tower-defense game without a controlled character can still have side-characters like a tutorial-NPC giving you tips on how to overcome certain challenges at the beginning of each stage. If you do have a protagonist that the player controls, then what’s he like? Does he have any abilities and powers? Keep in mind that this shouldn’t feel like a “How to Play” subsection.

Artificial Intelligence

Any game will need a persisting world to handle all the player’s actions to the game and the other way around. That includes enemy movements, player controls, collision handling, time counting, random number generators and many other things one could need in a game. Although people not directly related to the programming may not understand this subsection entirely, they should at least grasp the basic of it. Most of all, keep the coding out of here and simply state the enemies’ moving patterns, the chain puzzle piece falling algorithm, maybe illustrate the combat system with a flowchart and so on.

Example:

The characters on the board will escape the orbs using simple pathfinding / flocking algorithms. Every level will use up to three different script files to issue commands to the animated characters. (…) Player bots will be used to simulate real players. This will allow any level to be played even if there are more goals than players. The decision process that the A.I. system is trying to solve is this:

– Should I place a new block? If so:
– Where do I place the block?
– What type / material should the block be?

Technical Aspects Section

The technical aspects consist of a series of game data, such as the system requirements on which it will play and the framework in which it was developed, the method or algorithm it was based on, and the maximum number of elements that can be rendered on screen. The graphical technical aspects consists of software used, modeling type, art style and others according to these topics.

The system requirements are the necessary computer settings for the game to be played, like the size it occupies on the computer’s HD and how much RAM is needed.

System Requirements for Left4Dead

Another important technical aspect not to forget is the ESRB (Entertainment Software Rating Board) rating (or similar), already explained earlier. Some of the ratings are shown below.

Common ESRB Ratings

To Include or Not to Include? When? Why?

Technical aspects interest the companies that will distribute it or that will use the technology developed in the game, so always add something in it if you’re showing this to someone that will approve or disapprove the game. There has to be some care when writing technical aspects. You can write something in the wrong subject. For example: limiting the platform and distribution game mode belongs to Marketing Aspects, not to Technical Aspects.


More Examples

For professional examples of Design Documents provided by the developers, we have: Shred Nebula, Play With Fire, Grim Fandango Puzzle Document, and many more avaliable at gamepitches.com.

For more material about the structure and composition of a GDD, one could try the featured Gamasutra article The Anatomy of a Design Document, Part 1 and Part 2; the self explanatory Creating a Great Design Document; and a more general How to write an effective Design Document, which isn’t about GDD, but about software development.

More on Game Design: The Two C’s of Video Game Design.

Moreover, there are other visions of how should documentation be done in the Game Industry, as seen in Game Design Logs and Return of the GDD. Although they seem to contradict what had been told here, this should fall in a case-by-case analysis considering team size, budget and deadlines.


Conclusion

For designers who need the approval of an investor: truth be told, before you can make any progress with an investor, you must first get his attention, and to do so, the following key points of your document must be in excellent shape.

High concept: you never get a second chance to make a first impression, and here is where you will make it. We have already given you the tools to make this section, now just remember to give its construction a high priority and point everything that makes your game more appealing here.

Pictures: do not be fooled that the reader will always go through your entire GDD, there are some documents that surpass a thousand pages (yes, this is true!). But he will surely take a better look if something catches his attention, and what better way of doing so than with pictures? After all, one image is worth a thousand words.

It goes without saying that your document must have a great appearance. Take your time to make everything readable and nice. Also, don’t forget that this article only presented a skeleton structure of a GDD for you; you will have to adapt it to your own game!



View full post on Activetuts+

Nov 10, 2011 Posted on Nov 10, 2011 in Hints and Tips | 10 comments

TimelineLite Ultimate Starter Guide: Basic Methods and Properties

This entry is part 2 of 2 in the series TimelineLite Ultimate Starter Guide

In the first part of this series we took a general look at the capabilities of TimelineLite. In this video I’ll show you how to get up and running with your first TimelineLite animation. You’ll learn about the various methods and properties that will be a foundation for all of the lessons moving forward.


TimelineLite in Action

You can find all the files used to create the SWF above in the source files for this tutorial.


Watch the Screencast

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


TimelineLite Basic Methods

The following methods are used to add tweens to a TimelineLite. It’s very important to understand the subtle differences as covered in the video.

insert() – Adds tweens to a timeline at a specific time. If no insertion time is specified the tween will be inserted at a start time of zero seconds.

//this tween will be inserted at the beginning of the timeline
 tl.insert( TweenLite.to( mc, 1, {x:100} ) );
//this tween will be inserted 2 seconds into the timeline
 tl.insert( TweenLite.to( mc, 1, {x:100} ), 2);

append() – Adds tweens to a timeline relative to the end of the timeline. The offset value can be positive or negative. A negative offset will allow tweens to overlap.

//this tween will directly after all previous tweens have finished
 tl.append( TweenLite.to( mc, 1, {x:100} ) );
<pre>//this tween will play 1 second before all previous tweens have finished
 tl.append( TweenLite.to( mc, 1, {x:100} ), -1 );

prepend() – Adds tweens to the beginning of a timeline and pushes all existing tweens forward in time.

//this tween occur before any other tweens that exist in the timeline
 tl.prepend( TweenLite.to( mc, 1, {x:100} ) );

TimelineLite Basic Properties

The following properties are very useful for adding functionality to your timelines and for debugging:

  • timeScale – Multiplier describing the speed of the timeline where 1 is normal speed, 0.5 is half-speed, 2 is double speed, etc.
  • currentProgress – Value between 0 and 1 indicating the progress of the timeline according to its duration where 0 is at the beginning, 0.5 is halfway finished, and 1 is finished.
  • duration – Duration of the timeline in seconds

TimelineLite Special Properties

When constructing a TimelineLite you can pass a number of "special properties" into the constructor. The video demonstates onUpdate, onComplete, and paused. The special properties are all contained in a vars object.

//this timeline will be paused initially and when it is done
//it will call a function called completeHandler
tl = new TimelineLite( {onComplete:completeHandler, paused:true} );

TimelineLite has many more methods, properties and “special properties” which are too numerous to list here. I urge you to investigate all there is to offer in the Official TimelineLite Documentation. The ones listed above are the most important to understand when getting started. As this series progresses I will be introducing more of the tools you will be using to gain advanced control over the setup and playback of your animation sequences.

The next video in this series will focus on controlling a TimelineLite while it is playing. It will cover everything from basic play() and reverse() to adding an interactive scrubber control.


TimelineLite Code Sample

Below is a sample of the code used in the video to illustrate the basic structure of a TimelineLite.

			//constructor
			tl = new TimelineLite();

			//tweens that introduce car.
			//insert() puts them all at a time of 0 seconds
			tl.insert( TweenMax.from(gti_mc, .5, {x:-500, blurFilter:{blurX:140}}) );
			tl.insert( TweenLite.from(gti_mc.wheel1_mc, .5, {rotation:-180}) );
			tl.insert( TweenLite.from(gti_mc.wheel2_mc, .5, {rotation:-180}) );

			//append() adds tweens relative to the end of the timeline
			//.5 seconds after previous tweens end this text will show for 1 second and then fade out
			tl.append( TweenMax.from(hello_mc, .5, {alpha:0, repeat:1, repeatDelay:1, yoyo:true}) ,.5);

			//introduce second text .5 seconds after previous tween ends
			tl.append( TweenMax.from( colors_mc, .5, {alpha:0}), .5 );

			//tint sequence
			tl.append( TweenMax.to( gti_mc.body_mc, .2, {tint:blue}) , .5);
			tl.append( TweenMax.to( gti_mc.body_mc, .2, {tint:red}) , .5);
			tl.append( TweenMax.to( gti_mc.body_mc, .2, {tint:black}) , .5);

			//last text
			tl.append( TweenMax.from( black_mc, .5, {alpha:0}), 1 );

			//optional: inserts black box reveal at the beginning of the timeline
			tl.prepend( TweenLite.from ( cover_mc, .5, {y:0}) );



View full post on Activetuts+

Nov 9, 2011 Posted on Nov 9, 2011 in Hints and Tips | 10 comments

TimelineLite Ultimate Starter Guide: Introduction

This entry is part 1 of 1 in the series TimelineLite Ultimate Starter Guide

TimelineLite is the ultimate tool for creating elaborate and precise sequences of scripted animation. It is an integral part of the GreenSock Tweening Platform that allows you to make the most of TweenLite and TweenMax. This series of screencasts will walk you step by step through everything you need to know to take your AS3 tweening skills to the next level.


Basic Features of TimelineLite

  • Create a sequence of TweenLite/Max tweens
  • Play and pause any sequence
  • Reverse any sequence
  • Adjust the overall speed of the sequence
  • Jump-to any part of the sequence
  • Add labels for easy navigation
  • Scrub through any animation

Along the way we will be diving into TimelineMax which extends the power of TimelinLite with even more features. Everything you learn how to do in TimelineLite will also apply to TimelineMax.

Also, although this guide was produced solely with AS3, TimelineLite and TimelineMax have the exact same features in AS2, and use identical syntax!


Meet TimelineLite

In this first introductory video I’m going to explain exactly what TimelineLite is and what it can do. I’ll walk you through some inspiring examples of TimelineLite that highlight its many features. Along the way I’ll show you a few resources that are going to help you get the most out of your TimelineLite training. Once you see how concise and flexible TimelineLite code can be, you’ll never tween without it.

Sit back and relax as I set the groundwork for all the amazing things we will be covering in this series.

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


TimelineLite in Action


Resources Mentioned in this Video

In this series of videos I am going to be referring to the TimelineLite documentation many times. I strongly suggest you visit and bookmark the following:

  • GreenSock.com to learn more about TimelineLite and get the complete GreenSock Tweening Platform code library.
  • Official TimelineLite Documentation get ahead of the class and see the tremendous amount of properties and methods available.

To get the most out of TimelineLite its imperative that you have a basic understanding of TweenLite and TweenMax. For a quick crash course please read GreenSock’s Getting Started Tweening article.

Come back tomorrow for the next video in the series, where we’ll be looking at basic methods and properties of TimelineLite.



View full post on Activetuts+

Nov 8, 2011 Posted on Nov 8, 2011 in Hints and Tips | 10 comments

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.


Step 3: Interface

A colorful nice looking interface will be displayed, this involves multiple shapes, buttons and more.
Simple shapes were created using the Flash Drawing Tools so it won’t be necessary to include their creation.


Step 4: Instance Names

The image above shows the Instance Names used in the MovieClips. The ones that start with a Capital Letter are Library Class Names and should not be on stage.


Step 5: TweenNano

We’ll use a different tween engine from the default included in Flash, this will increase performace as well as being easier to use.

You can download TweenNano from its official website.


Step 6: QR Code Library

We’ll make use of a fantastic QR Code Encoder library which can be downloaded from here. You can learn more about using external libraries in your code with this tutorial.


Step 7: Set Main Class

Add the class name to the Class field in the Publish section of the Properties panel to associate the FLA with the Main document class.


Step 8: Create a New ActionScript Class

Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.


Step 9: Class Structure

Create your basic class structure to begin writing your code.

package
{
	import flash.display.Sprite;

	public class Main extends Sprite
	{
		public function Main():void
		{
			// constructor code
		}
	}
}

Step 10: Required Classes

These are the classes we’ll need to import for our class to work, the import directive makes externally defined classes and packages available to your code.

import flash.display.Sprite;
import flash.events.MouseEvent;
import org.qrcode.QRCode;
import flash.display.Bitmap;
import com.greensock.TweenNano;
import com.greensock.easing.Expo;

Step 11: Variables

These are the variables we’ll use, read the comments in the code to know more about them, some of their names are self explaining so there will be no comment there.

private var textView:TextView;
private var smsView:SMSView = new SMSView();
private var emailView:EmailView = new EmailView();
private var linkView:LinkView = new LinkView();
private var lastView:Sprite;
private var currentTarget:String; //current string to convert
private var qrImg:Bitmap;

Step 12: Constructor

The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object or runs using the Document Class.

It calls the necessary functions to start the app. Check those functions in the next steps.

public final function Main():void
{
	addTextView();
	addListeners();
}

Step 13: Add Text View

The first function executed by the constructor. It will instantiate the TextView and add it to the stage. This will be the default view that will be shown starting the application. It includes a call to remove the currently visible view (in case there’s one) and also performs a Tween as a detail to the interface.

private final function addTextView():void
{
	removeLastView();

	textView = new TextView();
	textView.x = stage.stageWidth * 0.5;
	textView.y = 110;
	addChild(textView);

	TweenNano.from(textView, 0.5, {y: textView.y - 10, alpha:0, ease:Expo});

	lastView = textView;
}

Step 14: SMS View

This code handles the SMSView position and animation. It is called when the SMS button tab is pressed.

private final function addSMSView():void
{
	removeLastView();

	smsView = new SMSView();
	smsView.x = stage.stageWidth * 0.5;
	smsView.y = 150;
	addChild(smsView);

	TweenNano.from(smsView, 0.5, {y: smsView.y - 10, alpha:0, ease:Expo});

	lastView = smsView;
}

Step 15: Email View

The EmailView code. It will place and animate this view on the stage.

private final function addEmailView():void
{
	removeLastView();

	emailView = new EmailView();
	emailView.x = stage.stageWidth * 0.5;
	emailView.y = 155;
	addChild(emailView);

	TweenNano.from(emailView, 0.5, {y: emailView.y - 10, alpha:0, ease:Expo});

	lastView = emailView;
}

Step 16: Link View

This is the final tab, it removes the last visible view and adds the LinkView to the stage.

private final function addLinkView():void
{
	removeLastView();

	linkView = new LinkView();
	linkView.x = stage.stageWidth * 0.5;
	linkView.y = 110;
	addChild(linkView);

	TweenNano.from(linkView, 0.5, {y: linkView.y - 10, alpha:0, ease:Expo});

	lastView = linkView;
}

Step 17: Remove Last View

This function removes the currently visible view from the stage and frees it up for garbage collection.

private final function removeLastView():void
{
	if(lastView != null)
	{
		removeChild(lastView);
		lastView = null;
	}
}

Step 18: Add Listeners

The next code links the buttons to their corresponding functions. This will enable the tab based navigation.

private final function addListeners():void
{
	abcBtn.addEventListener(MouseEvent.MOUSE_UP, indicatorHandler);
	smsBtn.addEventListener(MouseEvent.MOUSE_UP, indicatorHandler);
	emailBtn.addEventListener(MouseEvent.MOUSE_UP, indicatorHandler);
	linkBtn.addEventListener(MouseEvent.MOUSE_UP, indicatorHandler);
	refreshBtn.addEventListener(MouseEvent.MOUSE_UP, refreshCode);
}

Step 19: Indicator Handler

The Indicator MovieClip is the little arrow that shows the active tab. This function places it in the correct position and calls the tab function.

private final function indicatorHandler(e:MouseEvent):void
{
	indicator.x = e.target.x;

	switch(e.target.name)
	{
		case 'abcBtn':
			addTextView();
			break;
		case 'smsBtn':
			addSMSView();
			break;
		case 'emailBtn':
			addEmailView();
			break;
		case 'linkBtn':
			addLinkView();
			break;
		default:
			trace('Button Names Error');
	}
}

Step 20: Refresh QR Code

This function will run when the Refresh button is pressed, it determines the current string to convert and the QRObject encode() method to generate a bitmap that is next added to the stage.

private final function refreshCode(e:MouseEvent):void
{
	switch(lastView)
	{
		case textView:
			currentTarget = textView.textTF.text;
			break;
		case smsView:
			currentTarget = 'SMSTO:' + smsView.phoneTF.text + ':' + smsView.contentTF.text;
			break;
		case emailView:
			currentTarget = 'SMTP:' + emailView.toTF.text + ':' + emailView.subjectTF.text + ':' + emailView.bodyTF.text;
			break;
		case linkView:
			currentTarget = linkView.linkTF.text;
			if (currentTarget.indexOf('://') == -1)
			{
				currentTarget = 'http://' + currentTarget;	//automatically add http:// to the front of links if required
			}
			break;
		default:
			trace('Target Error');
	}

	if(qrImg != null)
	{
		removeChild(qrImg);
		qrImg = null;
	}

	var qrObj:QRCode = new QRCode();
	qrObj.encode(currentTarget);

	qrImg = new Bitmap(qrObj.bitmapData);

	qrImg.x = stage.stageWidth * 0.5 - (qrImg.width * 0.5);
	qrImg.y = 300 - (qrImg.height * 0.5);

	addChild(qrImg);

	TweenNano.from(qrImg, 1, {alpha:0, ease:Expo});
}

Conclusion

Use this application to generate your custom QR Codes and remember to explore the source files.

I hope you liked this tutorial, thank you for reading!



View full post on Activetuts+

Page 29 of 253« First«...1020...2728293031...405060...»Last »
search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • The Math and ActionScript of Curves: Drawing Quadratic and Cubic Curves
  • Weekend Lecture: Understanding Games, a Flash Game About Game Design
  • Weekend Lecture: Understanding Games, a Flash Game About Game Design
  • Workshop Coding Challenge: Fix This Breakout Game
  • Enable the Latest AIR SDK in Flash Professional CS5.5+
Tag Cloud
2011 ActionScript Active Activetuts+ Adobe animation Basic Basix Best Build Button Character Create Creating Critique Custom design Effect Effects Files Flash from Game Guide HTML5 Introduction Macromedia Motion Muzzle part Player Premium Professional Quick Silverlight Simple Text Tool Tutorial Tuts+ Tween Using Video website Workshop
About Our Site:

Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more

Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!

Go Back In Time
May 2012
M T W T F S S
« Apr    
 123456
78910111213
14151617181920
21222324252627
28293031  
Pretty Blank Box
top

Blogroll

  • Development Blog
  • Documentation
  • Plugins
  • Suggest Ideas
  • Support Forum
  • Themes
  • WordPress Planet

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Archives

  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
Powered by WordPress  |  Designed by Elegant Themes  |  Lightning Fast Hosting by Site 5 Hosting