logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
top
Aug 12, 2011 Posted on Aug 12, 2011 in Hints and Tips | 10 comments

Create a Nifty Polaroid Photo Viewer With Flash and Photoshop

Ever wanted to make a manageable and beautiful photo viewer app? In this tutorial, I’ll show you how to design and code a nifty Polaroid photo viewer, focusing on the design and tweening.


Final Result Preview

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


Section 1: Organization

In this section we’ll discuss our folder structure, also we’ll acquire our stock imagery.


Step 1: Creating Our Folders

First let’s create a folder in which our project will be located. We’ll name it “Polaroid Viewer”.

Afterwards just copy this folder structure:

The folder structure which we'll use in our tutorial

Step 2: Understanding Our Folder Structure

When creating very visual projects, it’s very important to first really know what you want to design. Inside the Design folder I always have my visual concepts and also in the Design folder I edit the images I’ll need for a project.

After I’ve finished working on my concept I proceed to making a working product, I do this inside the Project folder. Inside the Project folder is the very known bin, lib and src folder structure:

  • bin: Everything which is being exported and is needed to launch the final product, including data assets.
  • lib: Our Flash documents.
  • src: All our code, our own classes, as well as other frameworks.

Step 3: Acquire Stock Imagery

Now that we’ve created our folders, let’s proceed to the images. In this tutorial we’ll need at least two images:

  • A polaroid frame
  • A picture of a wooden floor

You’ll need a Stock Xchange account to download these images, if you don’t yet have one, you should sign up! It’s a website filled with free stock imagery!

Click the links to download the images, afterwards save or move them to our Design folder.

Also we’ll need images to place inside the polaroid frames. Here’s a list of images which I’ve used, but feel free to use your own images.

  • Image #1
  • Image #2
  • Image #3

Section 2: Design

In this section we’re going to edit our stock images. After doing so, we’ll import these images inside our Flash document, which we’ll create later.

We’re going to edit our images with Photoshop, I’ll be using CS5, however you can always use older versions. If you’re not so confident in your Photoshop skills, you can download the images which I’ve already edited. Just download the source files from this tutorial, and you can find the images inside the Edited Images folder.


Step 4: Preparing Our Wooden Floor

In the final example all our polaroid pictures lie on a wooden floor. We’re now going to create this background.

Create a New Document in Photoshop with the dimensions 600x600px.

Add the wooden texture image to the document. Scale it so you’re pleased with the final result.

Our background has been scaled down.

I’ve also added a Gradient Map, setting the colors to black and white.

Add a gradient map to our background

Lastly I’ve changed the gradient map’s transition to 80%. To do so, click on one of the lower arrows, and afterwards click on the dot in the middle of the gradient. Drag this dot to 80%.

Editing the Gradient Map

And voila! We’ve created our wooden background! Save it as a Photoshop Document (.psd) in our Design folder, and name it Background.psd.

Our background which we'll use in our project

Step 5: Preparing the Polaroid Frame

We want to place our own images inside the polaroid frame. We must do two things, we’ll first need to remove the polaroid frame from its (white) background, and also we’ll need to cut the “photo” part away.

To do this, we’ll first create a new 600x600px Photoshop document. Paste the polaroid picture inside the document, scale it down till it fits.

The polaroid frame image has been opened in Photoshop

Why do we scale the image down? Because we’re creating a 600x600px Flash document, and it’s unnecessary to have and load a huge image if we won’t even scale it larger than 600 px.


Step 6: Isolating the Polaroid Frame

Select the pen tool (P) and click around the polaroid frame’s outer edge. When working with the Pen tool, be sure to set the Pen tool in its Paths mode.

Set the Pen Tool to paths mode.

Press Control + Enter (Windows) or Cmd + Enter (Mac) to select your current path.

Select with the pen tool the outer area of the polaroid picture

With your path selected click on the “Add Layer Mask” button. We’ve now isolated the polaroid from its background!

Add a layer mask to the polaroid

Step 7: Cutting the Photo Part Away From the Polaroid Frame

This step is very similar to Design Step 4. Again select the pen tool, and click around the inner area of the polaroid’s frame. Afterwards select the current path with Ctrl + Enter/Cmd + Enter.

Select with the pen tool the inner area of the polaroid picture

Now Alt-click on the mask in the Layers Panel. You’re now editing the mask directly.

Editing the Layer Mask of our polaroid picture

Select the Marquee tool (M). Right-click your selection and select Fill > Black.

Alt-click again on the mask icon, to return back to our “normal” Layer view. We’ve successfully edited our mask and now our polaroid is ready for use. Let’s save the image as a Photoshop document (.psd), I’ve named my document Polaroid.psd.

The polaroid picture has been edited

Section 3: Flash

In this section we’re (finally) going to use Flash. We’re going to set our Flash document to use the folder bin for exporting, and the folder src for our code. Time to open Flash!


Step 8: Creating Our Flash Document

Create a new Flash Document (ActionScript 3.0) with Flash Professional. Set the dimensions to 600x600px and the framerate to 24 fps. Set the Document Class to Main. Also change the background to black (#000000). Save it as “Polaroid.fla”, inside the lib folder.


Step 9: Changing Our Publish Settings

Afterwards go to File > Publish Settings, change Polaroid.swf to ../bin/Polaroid.swf, you can uncheck the HTML option. Now everything we export (only a SWF) will be in the bin folder. Do not close the Publish Settings window.

Change our publish settings of our Flash Document

Step 10: Changing Our Source Path

Click the Flash tab. Afterwards click on the Settings button next to Script: ActionScript 3.0.

Now we can change the source path. You’ll see a folder icon with the text “.”, change that to “../src”.

Flash will use the src folder for all its classes.

Change the ActionScript settings of our Flash Document

Step 11: Importing Our Graphics to Flash

It’s now time to start importing our graphics in to our Flash Document. If you had any trouble with the images, you can always download the source files from this tutorial at the top. There’ll be a folder named “Edited Images”, inside there’ll be the edited images which you can use.

Create a new Flash Document (ActionScript 3.0) with Flash Professional. Set the dimensions to 600x600px and the framerate to 24 fps. Also change the background to black (#000000).

We’ve saved our images as .psd files because they work so greatly with other Adobe products, like Flash. After creating our document, select File > Import to Library and select Polaroid.psd and Background.psd. After doing so our library looks like this:

We've imported our assets in to our Flash Document's library

Step 12: Creating Our Background Sprite

Drag Background.psd from the Library to our stage, afterwards convert it to a movie clip. Name it Background, and check the box “Export for ActionScript”. Set the base class to flash.display.Sprite. After doing so, you can remove the background again from the stage.

Convert the background to a symbol

Why did I set Background’s base class to Sprite instead of the default base class MovieClip? Because the only difference between a MovieClip and a Sprite is that MovieClips can contain multiple frames, and Sprites cannot. We don’t need multiple frames for our Background, so let’s set the base class of Background to Sprite.


Step 13: Creating and Our Polaroid Movie Clip

Just like we did with our background, drag polaroid.psd from the Libary to our stage. Convert it to a movie clip and name it Polaroid, again check the Export for ActionScript box. Set the base class to flash.display.Sprite.


Step 14: Creating Our Polaroid’s Layers

Our Polaroid is still on the stage, double-click it, so we can edit it. So far Polaroid only has one layer, rename this layer to Polaroid Frame.

Create two new Layers, naming them Mask and Image Holder.

The layers inside the symbol Polaroid

Step 15: Creating the Image Holder

Our Polaroid will contain an image, this image must be displayed somewhere, this will be done in a movie clip named “Image Holder”.

Draw a rectangle of approximately the size as the “photo area” of the polaroid, do this in the Image Holder layer. It doesn’t matter which color the rectangle will be. After creating this rectangle, convert it to a movie clip, name it “Image Holder”.

Give Image Holder an instance name of imageHolder.


Step 16: Adding a Mask to the Image Holder

Image Holder will contain the images which we will load. Sometimes these images are too big — take for example a 400x100px image; this image is much too wide, and its edges would extend out of the polaroid. We want to prevent this. Therefore we must hide all imagery which extends outside of the Image Holder’s area.

To do this, we must create a mask. A mask tells a layer which part should be displayed, and which part should be hidden.

If we want every image to be displayed inside Image Holder, without any edges protruding, we should set the mask’s size to the same dimensions as Image Holder itself.

Copy Image Holder, and paste it in place with Ctrl + Shift + V (Windows) / Cmd + Shift + V (Mac) on the layer Mask. Afterwards break the copied Image Holder with Ctrl + B (Windows) / Cmd + B (Mac).

Lastly we must tell our Mask layer that it is a Mask. Right-click on the layer Mask and select the option Mask.


Section 4: Code

It’s time to start coding, if you had any trouble with the Flash Section, you can just copy the folder Flash Section Completed. Inside that folder is everything you need to start following these steps.


Step 17: Creating an XML File

To load our images, we’ll use an XML file. The XML file will tell our product where the images are located.

Open a text editor and type the following:

<images>
	<image>
		<file>IMAGE_1.jpg</file>
	</image>
	<image>
		<file>IMAGE_2.jpg</file>
	</image>
	<image>
		<file>IMAGE_3.jpg</file>
	</image>
</images>

You should change IMAGE_1.jpg, IMAGE_2.jpg, etc. to real filenames, which refer to images located inside the bin folder. If you don’t have any images, download the images that I mentioned in Step 3.

Save this XML file as images.xml, inside the bin folder.


Step 18: Which Classes Do We Need?

Before we start coding, it’s important to know which tasks our project must do:

  • We must load our images from an XML file.
  • We must display these images inside a Polaroid.
  • We must prevent other Polaroids from zooming in when we are already zoomed in on a Polaroid.

To code all these functionalities in one class would make that class extremely complex, it’s better to seperate each task to a different class.

  • ImageLoader: Will load the XML file and pass the images to PolaroidHolder.
  • PolaroidHolder: When it receives the images, it will create a Polaroid for every image, so it also makes sure that only one Polaroid is zoomed in at a time.
  • Polaroid: The image will be displayed inside this class.

Step 19: Creating Our Main Class

The Main class is the class which Polaroid.fla calls when it gets initiated.

Create a new ActionScript file and name it “Main.as”, save it inside the src folder. The Main class looks as follows.

package {

	import flash.display.MovieClip;

	public class Main extends MovieClip {

		public function Main():void {

		}
	}
}

It’s so empty because we first need to create our other classes, while we’re busy we’re going to keep on adding code to the Main class.


Step 20: Explaining Absolute and Relative File Paths

In this project we’re loading several assets: an xml file and various images. We can use relative file paths or absolute paths. Let me explain the difference with an example; we have the following folder structure:

An imaginary folder setup, we're using this example to understand the difference between absolute and relative file paths

Loader.swf must load image1.jpg. From its current position Loader.swf must “open” the images directory and load image1.jpg. We tell Loader.swf to load images/image1.jpg. This type of loading is called relative file path loading, because the url is relative to Loader.swf’s current position.

So how do you load image1.jpg, regardless of where Loader.swf is located? This is done with absolute file path loading. The file path starts from the upper core, from the root. If it’s on a computer, its root is a hard drive. We’re deploying our project online, so the root would be the site server.


Step 21: Why We Need Absolute File Paths

When our project is done, we’d like to deploy it. Most probably it would be embedded inside an HTML page. There’s one small problem. If Loader.swf wants to load, it will load from its current location, from the location of the HTML page. We don’t want this, and therefore we must use absolute file path loading.

Now comes the biggest problem, we won’t know the location of the HTML file. We need to find the absolute path to the .swf file, and edit that path so we can load our imagery.

We can get the absolute path to the .swf file with root.loaderInfo.url.

It’s time to create our ImageLoader class.


Step 22: Creating Our ImageLoader Class

Create a new ActionScript file and name it ImageLoader.as, save it inside the .src folder. The class looks like this, it has been thoroughly commented:

package  {
	//import the classes we need
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.display.Loader;
	import flash.display.Bitmap;
	import flash.display.Sprite;

	public class ImageLoader extends Sprite{
		//will load our xml
		private var xmlLoader:URLLoader = new URLLoader();

		//stores the xml
		private var xml:XML;

		//a list of file paths to the images
		private var imageFileList:XMLList;

		//the path to the .swf file
		private var swfPath:String;

		//the project folder path (where the folders bin, src and lib are located)
		private var projectPath:String;

		//we must know the title of our project, so we can edit the .swf url to get our projectPath
		private var projectTitle:String;

		//we need to count how many images we've already loaded
		private var count:uint = 0;

		//we must store the images, the images are Bitmaps
		public var images:Vector.<Bitmap> = new Vector.<Bitmap>;

		public function ImageLoader(_projectTitle:String) {
			//we must know when ImageLoader has been added, then we can figure out what the root's url is
			addEventListener(Event.ADDED, whenAdded);

			//store the project's title
			projectTitle = _projectTitle;

			//when imageLoader is done with loading, call xmlLoaded
			xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
		}

		private function whenAdded(event:Event):void {
			//store the swf path
			swfPath = root.loaderInfo.url;

			//get our projectPath
			projectPath = swfPath.substr(0, swfPath.length - projectTitle.length);
		}

		//this function will load the images from an xml, and store the images
		public function load(url:String):void {
			//load the xml, which we'll need to load the images
			xmlLoader.load(new URLRequest(projectPath + url));
		}

		private function xmlLoaded(event:Event):void {
			//store the xml, which xmlLoader has loaded
			xml = new XML(event.target.data);

			//store all the file links in an XMLList
			imageFileList = new XMLList(xml.image.file);

			//now that we have the file information, we can load the images
			loadImages();
		}

		private function loadImages():void {
			for each (var imageFile:String in imageFileList){
				//create
				var imageLoader:Loader = new Loader();
				//whenever an image has been loaded, call imageLoaded
				imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded, false, 0, true);
				imageLoader.load(new URLRequest(projectPath + imageFile));
			}
		}

		private function imageLoaded(event:Event):void {
			//we're counting how many images we've already loaded, we've just loaded (another) one
			count++;

			//get the image Bitmap
			var image:Bitmap = Bitmap(event.target.loader.content);

			//store the image in our images Vector
			images.push(image);

			//if this is the last image we needed to load
			if(count == imageFileList.length()){
				//we're done, dispatch an event
				dispatchEvent(new Event('imagesLoaded'));
			}

			//--cleanup
			//unload the loader
			event.target.loader.unload();
		}

		public function cleanUp():void {
			xmlLoader.data = null;
			xmlLoader = null;
			xml = null;
			imageFileList = null;
			count = 0;
			images = null;
		}
	}

}

Step 23: Improving Our Main Class

Now that we have our ImageLoader class, we can improve our Main class.

package {

	import flash.display.MovieClip;
	import flash.events.Event;

	public class Main extends MovieClip {
		//a custom class we've made which will load all images from an xml file as Bitmaps
		private var imageLoader:ImageLoader;

		//this class will hold and display all our Polaroids
		private var polaroidHolder:PolaroidHolder;

		public function Main():void {
			//load our images, give imageLoader the name of the .swf file, so it can load using absolute paths
			imageLoader = new ImageLoader('Polaroid.swf');
			addChild(imageLoader);
			imageLoader.addEventListener('imagesLoaded', displayImages, false, 0, true);
			imageLoader.load('pictures.xml');
		}

		private function displayImages(event:Event):void {
			//we've loaded all our images
			polaroidHolder = new PolaroidHolder(imageLoader.images);
			addChild(polaroidHolder);

			//also clean up the imageLoader
			imageLoader.cleanUp();
			imageLoader = null;
		}
	}
}

Step 24: Creating Our PolaroidHolder Class

The PolaroidHolder will receive the images as a Vector. After receiving the images, it will create a Polaroid for each image. Let’s create our PolaroidHolder class:

package {
	import flash.display.MovieClip;
	import flash.display.Bitmap;
	import flash.events.MouseEvent;

	public class PolaroidHolder extends MovieClip {

		//this vector will hold all our Polaroids
		public var polaroids:Vector.<Polaroid>  = new Vector.<Polaroid>;
		//with this variable we no
		private var zoomedIn:Boolean;
		//the Polaroid we're zoomed in on
		private var currentPolaroid:Polaroid;

		public function PolaroidHolder(images:Vector.<Bitmap>) {
			// constructor code
			for each (var image:Bitmap in images) {
				//create a new Polaroid
				var polaroid:Polaroid = new Polaroid(image);

				//position and rotate it
				polaroid.x = Math.random() * 200 + 100;
				polaroid.y = Math.random() * 200;
				polaroid.rotation = Math.random() * 60 - 30;

				//add a clicking eventListener
				polaroid.addEventListener(MouseEvent.CLICK, onPolaroidClick);
				addChild(polaroid);

				//add it to the polaroids vector
				polaroids.push(polaroid);
			}
		}

		private function onPolaroidClick(event:MouseEvent):void {
			//there's been a click on a Polaroid!
			if (currentPolaroid == null) {
				//no currentPolaroid has been set, we're zooming in
				//set the clicked Polaroid as the current Polaroid
				currentPolaroid = event.currentTarget as Polaroid;

				//mute all other Polaroids (the ones which aren't zoomed in)
				for each (var polaroid:Polaroid in polaroids) {
					if (polaroid != currentPolaroid) {
						polaroid.mute();
					}
				}
			} else {
				//check if the click was on the current polaroid
				if (event.currentTarget == currentPolaroid) {
					//the same polaroid has been clicked (again), time to zoom out

					//unmute all other Polaroids, they can respond again to events
					for each (var polaroid:Polaroid in polaroids) {
						if (polaroid != currentPolaroid) {
							polaroid.unmute();
						}
					}

					//now we're not zoomed in, so we don't have a current polaroid
					currentPolaroid = null;
				}
			}
		}

	}

}

In lines 50 and 62, we call the functions mute() and unmute(). Mute makes the Polaroid numb to all events, it won’t respond to mouse overs, or clicks. This is precisely what we want when we’re zoomed in. We don’t want other Polaroids to do anything. After we’re zooming out, we want the Polaroids to respond to events; by calling unmute, the Polaroids will respond again to mouse overs and clicks.


Step 25: Creating Our Polaroid Class

Now it’s time to create our most interesting class, our Polaroid class! For this class we’ll need the popular tweening library tweener. Download it, and save the library inside the src folder (see this guide for more details).

package {
	import flash.display.MovieClip;
	import flash.events.MouseEvent;

	import caurina.transitions.*;
	import caurina.transitions.properties.*;
	import flash.display.Bitmap;
	import flash.events.Event;

	public class Polaroid extends MovieClip {

		//the scale at which the Polaroid is zoomed in
		private static const ZOOMED_IN_SCALE:Number = 1;
		//the scale at which the Polaroid is zoomed out
		private static const ZOOMED_OUT_SCALE:Number = .6;

		//the max height an image can be
		private var IMAGE_MAX_HEIGHT:Number;
		//the max width an image can be
		private var IMAGE_MAX_WIDTH:Number;

		//we must scale the loaded images, remember the scale
		private var scale:Number;

		//when we zoom out, we zoom out back to the Polaroid's original position and rotation
		//the Polaroid's original x coordinate.
		private var origX:Number;
		//we also need the original y coordinate
		private var origY:Number;
		//store the Polaroid's original rotation
		private var origRotation:Number;
		//when this Boolean becomes true, the Polaroid will not respond to mouse events
		private var muted:Boolean;
		//we need to know if the Polaroid has been clicked
		public var clicked:Boolean;

		public function Polaroid(image:Bitmap) {
			//make the Polaroid a button
			buttonMode = true;

			//the maximum dimensions for an image are limited by the dimensions of imageHolder
			IMAGE_MAX_HEIGHT = imageHolder.height;
			IMAGE_MAX_WIDTH = imageHolder.width;

			//scale the Polaroid down
			scaleX = ZOOMED_OUT_SCALE;
			scaleY = ZOOMED_OUT_SCALE;

			//we'll need to resize the image to make it fit
			//first check if it is a portrait or landscape
			if (image.width > image.height) {
				//it is a landscape
				//the scale is limited by the image's height
				scale = IMAGE_MAX_HEIGHT / image.height;
			} else {
				//it is a portrait
				//the scale is limited by the image's width
				scale = IMAGE_MAX_WIDTH / image.width;
			}

			//scale the image
			image.scaleX = scale;
			image.scaleY = scale;

			//add the scaled image
			imageHolder.addChild(image);

			//add event listeners to the Polaroid;
			addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
			addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
			addEventListener(MouseEvent.CLICK, onClick);
			addEventListener(Event.ADDED, whenAdded);
		}

		public function mute():void {
			//calling this function will make the Polaroid not respond to events
			buttonMode = false;
			muted = true;
		}

		public function unmute():void {
			//calling this function will make the Polaroid respond to events
			buttonMode = true;
			muted = false;
		}

		private function whenAdded(event:Event):void {
			//store the Polaroid's original coordinates and rotation
			origX = x;
			origY = y;
			origRotation = rotation;

			//we won't need this event listener anymore, remove it
			removeEventListener(Event.ADDED, whenAdded);
		}

		private function onMouseOver(event:MouseEvent):void {
			//only respond if the Polaroid has not been muted
			if (! muted) {
				//only respond if the Polaroid has not been clicked, clicked Polaroids should not respond to mouse overs.
				if (! clicked) {
					//move the polaroid to the front
					parent.setChildIndex(this, parent.numChildren - 1);
					//move and turn the polaroid in a random direction
					Tweener.addTween(this, {x: origX + Math.random() * 30 - 15, y: origY + Math.random() * 30 -15, rotation:origRotation + Math.random() * 20 - 10, time:1});
				}
			}
		}

		private function onMouseOut(event:MouseEvent):void {
			//only respond if the Polaroid has not been muted
			if (! muted) {
				//only respond if the Polaroid has not been clicked
				if (! clicked) {
					//move the polaroid back to it's original position and rotation
					Tweener.addTween(this, {x: origX, y:origY, rotation:origRotation, time:1});
				}
			}
		}

		private function onClick(event:MouseEvent):void {
			//only respond if the Polaroid has not been muted
			if (! muted) {
				//if it hasn't been clicked before
				if (! clicked) {
					//we've been clicked, let's make that true
					clicked = true;

					//we're zooming in, let's dispatch an event (Main will pick this up)
					dispatchEvent(new Event('zoomIn'));

					//zoom the Polaroid in to the center of the stage
					Tweener.addTween(this, {x:stage.stageWidth/2 - width/2, y:stage.stageHeight/2 - height/2, rotation:0, scaleX:ZOOMED_IN_SCALE, scaleY:ZOOMED_IN_SCALE, time: 1});
				} else {
					//we've already been clicked, so make clicked false
					clicked = false;

					//we're zooming out, let's dispatch an event (Main will pick this up)
					dispatchEvent(new Event('zoomOut'));

					//zoom the polaroid out, back to its original position
					Tweener.addTween(this, {x: origX, y:origY, rotation:origRotation, scaleX: ZOOMED_OUT_SCALE, scaleY:ZOOMED_OUT_SCALE, time:1});
				}
			}
		}
	}
}

Step 26: Adding Our PolaroidHolder to Our Main Class

Make the changes as seen in the code below.

package {

	import flash.display.MovieClip;

	public class Main extends MovieClip {

		//a custom class we've made which will load all images from an xml file as Bitmaps
		private var imageLoader:ImageLoader;

		private var polaroidHolder:PolaroidHolder;

		public function Main():void {
			//load our imagges
			imageLoader = new ImageLoader();
			imageLoader.addEventListener('imagesLoaded', displayImages, false, 0, true);
			imageLoader.load('pictures.xml');
		}

		private function displayImages(event:Event):void {
			//we've loaded all our images
			polaroidHolder = new PolaroidHolder(imageLoader.polaroids);
			addChild(polaroidHolder);

			//also clean up the imageLoader
			imageLoader.cleanUp();
			imageLoader = null;
		}
	}
}

Step 27: The Result So Far

It seems to work, but it’s not very interesting. When zooming in, the user is not “pulled in”, our product is not immersive enough. What we need is a background! By chance we created one in Step 4. Time to add our background!


Step 28: Adding Our Background

We had exported our background with the class Background.

Not only will we add Background as a child of Main, we’ll also make Background darken when we’re zoomed in, and lighten when we’re zoomed out. How do we do this? Whenever a Polaroid is clicked, it dispatches a custom event, zoomIn or zoomOut. We can trace this event, just add event listeners to our Main class, they’ll pick up the zoomIn and zoomOut events, and whenever they’re picked up, we can tell our Background to lighten or darken:

package {

	import flash.display.MovieClip;
	import flash.events.Event;

	import caurina.transitions.*;
	import caurina.transitions.properties.*;

	public class Main extends MovieClip {

		//a custom class we've made which will load all images from an xml file as Bitmaps
		private var imageLoader:ImageLoader;

		//this class will display all our Polaroids, by receiving a Vector of Bitmaps
		private var polaroidHolder:PolaroidHolder;

		//the wooden background, bg is an abbrivation for background
		private var bg:Background

		public function Main():void {
			//load our images
			imageLoader = new ImageLoader('Polaroid.swf');
			imageLoader.addEventListener('imagesLoaded', displayImages, false, 0, true);
			addChild(imageLoader);
			imageLoader.load('pictures.xml');

			//add our bg as a child
			bg = new Background();
			addChild(bg);

			//add event listener, so we know when we're zoomed in or out
			//3rd parameter of addEventListener is true, so we can capture the event, when it "bubbles" up from the Polaroid
			addEventListener('zoomIn', onZoomIn, true);
			addEventListener('zoomOut', onZoomOut, true);
		}

		private function displayImages(event:Event):void {
			//we've loaded all our images
			polaroidHolder = new PolaroidHolder(imageLoader.images);
			addChild(polaroidHolder);

			//also clean up the imageLoader
			imageLoader.cleanUp();
			imageLoader = null;
		}

		private function onZoomIn(event:Event):void {
			//upon zooming in, we'll darken the bg
			Tweener.addTween(bg, {alpha:.6, time:1});
		}

		private function onZoomOut(event:Event):void {
			//upon zooming out, we'll lighten the bg
			Tweener.addTween(bg, {alpha:1, time:1});
		}
	}
}

Step 29: Looking Back

Tada! We’re done, this was quite a tutorial! I hope you guys had fun following this tutorial, and also learnt something from it. Why not play around with the code? You could try adding text fields and somehow display the title of the image. Or use several types of Polaroids. Thanks, and feel free to comment if you have any questions or comments. Keep an eye out for my next tutorial!



View full post on Activetuts+

banner ad

10 Responses to “Create a Nifty Polaroid Photo Viewer With Flash and Photoshop”

  1. Daniel Apt says:
    August 12, 2011 at 4:59 pm

    Ever wanted to make a manageable and beautiful photo viewer app? In this tutorial, I’ll show you how to design and code a nifty Polaroid photo viewer, focusing on the design and tweening.


    Final Result Preview

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


    Section 1: Organization

    In this section we’ll discuss our folder structure, also we’ll acquire our stock imagery.


    Step 1: Creating Our Folders

    First let’s create a folder in which our project will be located. We’ll name it “Polaroid Viewer”.

    Afterwards just copy this folder structure:

    The folder structure which we'll use in our tutorial

    Step 2: Understanding Our Folder Structure

    When creating very visual projects, it’s very important to first really know what you want to design. Inside the Design folder I always have my visual concepts and also in the Design folder I edit the images I’ll need for a project.

    After I’ve finished working on my concept I proceed to making a working product, I do this inside the Project folder. Inside the Project folder is the very known bin, lib and src folder structure:

    • bin: Everything which is being exported and is needed to launch the final product, including data assets.
    • lib: Our Flash documents.
    • src: All our code, our own classes, as well as other frameworks.

    Step 3: Acquire Stock Imagery

    Now that we’ve created our folders, let’s proceed to the images. In this tutorial we’ll need at least two images:

    • A polaroid frame
    • A picture of a wooden floor

    You’ll need a Stock Xchange account to download these images, if you don’t yet have one, you should sign up! It’s a website filled with free stock imagery!

    Click the links to download the images, afterwards save or move them to our Design folder.

    Also we’ll need images to place inside the polaroid frames. Here’s a list of images which I’ve used, but feel free to use your own images.

    • Image #1
    • Image #2
    • Image #3

    Section 2: Design

    In this section we’re going to edit our stock images. After doing so, we’ll import these images inside our Flash document, which we’ll create later.

    We’re going to edit our images with Photoshop, I’ll be using CS5, however you can always use older versions. If you’re not so confident in your Photoshop skills, you can download the images which I’ve already edited. Just download the source files from this tutorial, and you can find the images inside the Edited Images folder.


    Step 4: Preparing Our Wooden Floor

    In the final example all our polaroid pictures lie on a wooden floor. We’re now going to create this background.

    Create a New Document in Photoshop with the dimensions 600x600px.

    Add the wooden texture image to the document. Scale it so you’re pleased with the final result.

    Our background has been scaled down.

    I’ve also added a Gradient Map, setting the colors to black and white.

    Add a gradient map to our background

    Lastly I’ve changed the gradient map’s transition to 80%. To do so, click on one of the lower arrows, and afterwards click on the dot in the middle of the gradient. Drag this dot to 80%.

    Editing the Gradient Map

    And voila! We’ve created our wooden background! Save it as a Photoshop Document (.psd) in our Design folder, and name it Background.psd.

    Our background which we'll use in our project

    Step 5: Preparing the Polaroid Frame

    We want to place our own images inside the polaroid frame. We must do two things, we’ll first need to remove the polaroid frame from its (white) background, and also we’ll need to cut the “photo” part away.

    To do this, we’ll first create a new 600x600px Photoshop document. Paste the polaroid picture inside the document, scale it down till it fits.

    The polaroid frame image has been opened in Photoshop

    Why do we scale the image down? Because we’re creating a 600x600px Flash document, and it’s unnecessary to have and load a huge image if we won’t even scale it larger than 600 px.


    Step 6: Isolating the Polaroid Frame

    Select the pen tool (P) and click around the polaroid frame’s outer edge. When working with the Pen tool, be sure to set the Pen tool in its Paths mode.

    Set the Pen Tool to paths mode.

    Press Control + Enter (Windows) or Cmd + Enter (Mac) to select your current path.

    Select with the pen tool the outer area of the polaroid picture

    With your path selected click on the “Add Layer Mask” button. We’ve now isolated the polaroid from its background!

    Add a layer mask to the polaroid

    Step 7: Cutting the Photo Part Away From the Polaroid Frame

    This step is very similar to Design Step 4. Again select the pen tool, and click around the inner area of the polaroid’s frame. Afterwards select the current path with Ctrl + Enter/Cmd + Enter.

    Select with the pen tool the inner area of the polaroid picture

    Now Alt-click on the mask in the Layers Panel. You’re now editing the mask directly.

    Editing the Layer Mask of our polaroid picture

    Select the Marquee tool (M). Right-click your selection and select Fill > Black.

    Alt-click again on the mask icon, to return back to our “normal” Layer view. We’ve successfully edited our mask and now our polaroid is ready for use. Let’s save the image as a Photoshop document (.psd), I’ve named my document Polaroid.psd.

    The polaroid picture has been edited

    Section 3: Flash

    In this section we’re (finally) going to use Flash. We’re going to set our Flash document to use the folder bin for exporting, and the folder src for our code. Time to open Flash!


    Step 8: Creating Our Flash Document

    Create a new Flash Document (ActionScript 3.0) with Flash Professional. Set the dimensions to 600x600px and the framerate to 24 fps. Set the Document Class to Main. Also change the background to black (#000000). Save it as “Polaroid.fla”, inside the lib folder.


    Step 9: Changing Our Publish Settings

    Afterwards go to File > Publish Settings, change Polaroid.swf to ../bin/Polaroid.swf, you can uncheck the HTML option. Now everything we export (only a SWF) will be in the bin folder. Do not close the Publish Settings window.

    Change our publish settings of our Flash Document

    Step 10: Changing Our Source Path

    Click the Flash tab. Afterwards click on the Settings button next to Script: ActionScript 3.0.

    Now we can change the source path. You’ll see a folder icon with the text “.”, change that to “../src”.

    Flash will use the src folder for all its classes.

    Change the ActionScript settings of our Flash Document

    Step 11: Importing Our Graphics to Flash

    It’s now time to start importing our graphics in to our Flash Document. If you had any trouble with the images, you can always download the source files from this tutorial at the top. There’ll be a folder named “Edited Images”, inside there’ll be the edited images which you can use.

    Create a new Flash Document (ActionScript 3.0) with Flash Professional. Set the dimensions to 600x600px and the framerate to 24 fps. Also change the background to black (#000000).

    We’ve saved our images as .psd files because they work so greatly with other Adobe products, like Flash. After creating our document, select File > Import to Library and select Polaroid.psd and Background.psd. After doing so our library looks like this:

    We've imported our assets in to our Flash Document's library

    Step 12: Creating Our Background Sprite

    Drag Background.psd from the Library to our stage, afterwards convert it to a movie clip. Name it Background, and check the box “Export for ActionScript”. Set the base class to flash.display.Sprite. After doing so, you can remove the background again from the stage.

    Convert the background to a symbol

    Why did I set Background’s base class to Sprite instead of the default base class MovieClip? Because the only difference between a MovieClip and a Sprite is that MovieClips can contain multiple frames, and Sprites cannot. We don’t need multiple frames for our Background, so let’s set the base class of Background to Sprite.


    Step 13: Creating and Our Polaroid Movie Clip

    Just like we did with our background, drag polaroid.psd from the Libary to our stage. Convert it to a movie clip and name it Polaroid, again check the Export for ActionScript box. Set the base class to flash.display.Sprite.


    Step 14: Creating Our Polaroid’s Layers

    Our Polaroid is still on the stage, double-click it, so we can edit it. So far Polaroid only has one layer, rename this layer to Polaroid Frame.

    Create two new Layers, naming them Mask and Image Holder.

    The layers inside the symbol Polaroid

    Step 15: Creating the Image Holder

    Our Polaroid will contain an image, this image must be displayed somewhere, this will be done in a movie clip named “Image Holder”.

    Draw a rectangle of approximately the size as the “photo area” of the polaroid, do this in the Image Holder layer. It doesn’t matter which color the rectangle will be. After creating this rectangle, convert it to a movie clip, name it “Image Holder”.

    Give Image Holder an instance name of imageHolder.


    Step 16: Adding a Mask to the Image Holder

    Image Holder will contain the images which we will load. Sometimes these images are too big — take for example a 400x100px image; this image is much too wide, and its edges would extend out of the polaroid. We want to prevent this. Therefore we must hide all imagery which extends outside of the Image Holder’s area.

    To do this, we must create a mask. A mask tells a layer which part should be displayed, and which part should be hidden.

    If we want every image to be displayed inside Image Holder, without any edges protruding, we should set the mask’s size to the same dimensions as Image Holder itself.

    Copy Image Holder, and paste it in place with Ctrl + Shift + V (Windows) / Cmd + Shift + V (Mac) on the layer Mask. Afterwards break the copied Image Holder with Ctrl + B (Windows) / Cmd + B (Mac).

    Lastly we must tell our Mask layer that it is a Mask. Right-click on the layer Mask and select the option Mask.


    Section 4: Code

    It’s time to start coding, if you had any trouble with the Flash Section, you can just copy the folder Flash Section Completed. Inside that folder is everything you need to start following these steps.


    Step 17: Creating an XML File

    To load our images, we’ll use an XML file. The XML file will tell our product where the images are located.

    Open a text editor and type the following:

    
    
    <images>
    	<image>
    		<file>IMAGE_1.jpg</file>
    	</image>
    	<image>
    		<file>IMAGE_2.jpg</file>
    	</image>
    	<image>
    		<file>IMAGE_3.jpg</file>
    	</image>
    </images>
    

    You should change IMAGE_1.jpg, IMAGE_2.jpg, etc. to real filenames, which refer to images located inside the bin folder. If you don’t have any images, download the images that I mentioned in Step 3.

    Save this XML file as images.xml, inside the bin folder.


    Step 18: Which Classes Do We Need?

    Before we start coding, it’s important to know which tasks our project must do:

    • We must load our images from an XML file.
    • We must display these images inside a Polaroid.
    • We must prevent other Polaroids from zooming in when we are already zoomed in on a Polaroid.

    To code all these functionalities in one class would make that class extremely complex, it’s better to seperate each task to a different class.

    • ImageLoader: Will load the XML file and pass the images to PolaroidHolder.
    • PolaroidHolder: When it receives the images, it will create a Polaroid for every image, so it also makes sure that only one Polaroid is zoomed in at a time.
    • Polaroid: The image will be displayed inside this class.

    Step 19: Creating Our Main Class

    The Main class is the class which Polaroid.fla calls when it gets initiated.

    Create a new ActionScript file and name it “Main.as”, save it inside the src folder. The Main class looks as follows.

    
    
    package {
    
    	import flash.display.MovieClip;
    
    	public class Main extends MovieClip {
    
    		public function Main():void {
    
    		}
    	}
    }
    

    It’s so empty because we first need to create our other classes, while we’re busy we’re going to keep on adding code to the Main class.


    Step 20: Explaining Absolute and Relative File Paths

    In this project we’re loading several assets: an xml file and various images. We can use relative file paths or absolute paths. Let me explain the difference with an example; we have the following folder structure:

    An imaginary folder setup, we're using this example to understand the difference between absolute and relative file paths

    Loader.swf must load image1.jpg. From its current position Loader.swf must “open” the images directory and load image1.jpg. We tell Loader.swf to load images/image1.jpg. This type of loading is called relative file path loading, because the url is relative to Loader.swf’s current position.

    So how do you load image1.jpg, regardless of where Loader.swf is located? This is done with absolute file path loading. The file path starts from the upper core, from the root. If it’s on a computer, its root is a hard drive. We’re deploying our project online, so the root would be the site server.


    Step 21: Why We Need Absolute File Paths

    When our project is done, we’d like to deploy it. Most probably it would be embedded inside an HTML page. There’s one small problem. If Loader.swf wants to load, it will load from its current location, from the location of the HTML page. We don’t want this, and therefore we must use absolute file path loading.

    Now comes the biggest problem, we won’t know the location of the HTML file. We need to find the absolute path to the .swf file, and edit that path so we can load our imagery.

    We can get the absolute path to the .swf file with root.loaderInfo.url.

    It’s time to create our ImageLoader class.


    Step 22: Creating Our ImageLoader Class

    Create a new ActionScript file and name it ImageLoader.as, save it inside the .src folder. The class looks like this, it has been thoroughly commented:

    
    
    package  {
    	//import the classes we need
    	import flash.net.URLLoader;
    	import flash.net.URLRequest;
    	import flash.events.Event;
    	import flash.display.Loader;
    	import flash.display.Bitmap;
    	import flash.display.Sprite;
    
    	public class ImageLoader extends Sprite{
    		//will load our xml
    		private var xmlLoader:URLLoader = new URLLoader();
    
    		//stores the xml
    		private var xml:XML;
    
    		//a list of file paths to the images
    		private var imageFileList:XMLList;
    
    		//the path to the .swf file
    		private var swfPath:String;
    
    		//the project folder path (where the folders bin, src and lib are located)
    		private var projectPath:String;
    
    		//we must know the title of our project, so we can edit the .swf url to get our projectPath
    		private var projectTitle:String;
    
    		//we need to count how many images we've already loaded
    		private var count:uint = 0;
    
    		//we must store the images, the images are Bitmaps
    		public var images:Vector.<Bitmap> = new Vector.<Bitmap>;
    
    		public function ImageLoader(_projectTitle:String) {
    			//we must know when ImageLoader has been added, then we can figure out what the root's url is
    			addEventListener(Event.ADDED, whenAdded);
    
    			//store the project's title
    			projectTitle = _projectTitle;
    
    			//when imageLoader is done with loading, call xmlLoaded
    			xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
    		}
    
    		private function whenAdded(event:Event):void {
    			//store the swf path
    			swfPath = root.loaderInfo.url;
    
    			//get our projectPath
    			projectPath = swfPath.substr(0, swfPath.length - projectTitle.length);
    		}
    
    		//this function will load the images from an xml, and store the images
    		public function load(url:String):void {
    			//load the xml, which we'll need to load the images
    			xmlLoader.load(new URLRequest(projectPath + url));
    		}
    
    		private function xmlLoaded(event:Event):void {
    			//store the xml, which xmlLoader has loaded
    			xml = new XML(event.target.data);
    
    			//store all the file links in an XMLList
    			imageFileList = new XMLList(xml.image.file);
    
    			//now that we have the file information, we can load the images
    			loadImages();
    		}
    
    		private function loadImages():void {
    			for each (var imageFile:String in imageFileList){
    				//create
    				var imageLoader:Loader = new Loader();
    				//whenever an image has been loaded, call imageLoaded
    				imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded, false, 0, true);
    				imageLoader.load(new URLRequest(projectPath + imageFile));
    			}
    		}
    
    		private function imageLoaded(event:Event):void {
    			//we're counting how many images we've already loaded, we've just loaded (another) one
    			count++;
    
    			//get the image Bitmap
    			var image:Bitmap = Bitmap(event.target.loader.content);
    
    			//store the image in our images Vector
    			images.push(image);
    
    			//if this is the last image we needed to load
    			if(count == imageFileList.length()){
    				//we're done, dispatch an event
    				dispatchEvent(new Event('imagesLoaded'));
    			}
    
    			//--cleanup
    			//unload the loader
    			event.target.loader.unload();
    		}
    
    		public function cleanUp():void {
    			xmlLoader.data = null;
    			xmlLoader = null;
    			xml = null;
    			imageFileList = null;
    			count = 0;
    			images = null;
    		}
    	}
    
    }
    

    Step 23: Improving Our Main Class

    Now that we have our ImageLoader class, we can improve our Main class.

    
    
    package {
    
    	import flash.display.MovieClip;
    	import flash.events.Event;
    
    	public class Main extends MovieClip {
    		//a custom class we've made which will load all images from an xml file as Bitmaps
    		private var imageLoader:ImageLoader;
    
    		//this class will hold and display all our Polaroids
    		private var polaroidHolder:PolaroidHolder;
    
    		public function Main():void {
    			//load our images, give imageLoader the name of the .swf file, so it can load using absolute paths
    			imageLoader = new ImageLoader('Polaroid.swf');
    			addChild(imageLoader);
    			imageLoader.addEventListener('imagesLoaded', displayImages, false, 0, true);
    			imageLoader.load('pictures.xml');
    		}
    
    		private function displayImages(event:Event):void {
    			//we've loaded all our images
    			polaroidHolder = new PolaroidHolder(imageLoader.images);
    			addChild(polaroidHolder);
    
    			//also clean up the imageLoader
    			imageLoader.cleanUp();
    			imageLoader = null;
    		}
    	}
    }
    

    Step 24: Creating Our PolaroidHolder Class

    The PolaroidHolder will receive the images as a Vector. After receiving the images, it will create a Polaroid for each image. Let’s create our PolaroidHolder class:

    
    
    package {
    	import flash.display.MovieClip;
    	import flash.display.Bitmap;
    	import flash.events.MouseEvent;
    
    	public class PolaroidHolder extends MovieClip {
    
    		//this vector will hold all our Polaroids
    		public var polaroids:Vector.<Polaroid>  = new Vector.<Polaroid>;
    		//with this variable we no
    		private var zoomedIn:Boolean;
    		//the Polaroid we're zoomed in on
    		private var currentPolaroid:Polaroid;
    
    		public function PolaroidHolder(images:Vector.<Bitmap>) {
    			// constructor code
    			for each (var image:Bitmap in images) {
    				//create a new Polaroid
    				var polaroid:Polaroid = new Polaroid(image);
    
    				//position and rotate it
    				polaroid.x = Math.random() * 200 + 100;
    				polaroid.y = Math.random() * 200;
    				polaroid.rotation = Math.random() * 60 - 30;
    
    				//add a clicking eventListener
    				polaroid.addEventListener(MouseEvent.CLICK, onPolaroidClick);
    				addChild(polaroid);
    
    				//add it to the polaroids vector
    				polaroids.push(polaroid);
    			}
    		}
    
    		private function onPolaroidClick(event:MouseEvent):void {
    			//there's been a click on a Polaroid!
    			if (currentPolaroid == null) {
    				//no currentPolaroid has been set, we're zooming in
    				//set the clicked Polaroid as the current Polaroid
    				currentPolaroid = event.currentTarget as Polaroid;
    
    				//mute all other Polaroids (the ones which aren't zoomed in)
    				for each (var polaroid:Polaroid in polaroids) {
    					if (polaroid != currentPolaroid) {
    						polaroid.mute();
    					}
    				}
    			} else {
    				//check if the click was on the current polaroid
    				if (event.currentTarget == currentPolaroid) {
    					//the same polaroid has been clicked (again), time to zoom out
    
    					//unmute all other Polaroids, they can respond again to events
    					for each (var polaroid:Polaroid in polaroids) {
    						if (polaroid != currentPolaroid) {
    							polaroid.unmute();
    						}
    					}
    
    					//now we're not zoomed in, so we don't have a current polaroid
    					currentPolaroid = null;
    				}
    			}
    		}
    
    	}
    
    }

    In lines 50 and 62, we call the functions mute() and unmute(). Mute makes the Polaroid numb to all events, it won’t respond to mouse overs, or clicks. This is precisely what we want when we’re zoomed in. We don’t want other Polaroids to do anything. After we’re zooming out, we want the Polaroids to respond to events; by calling unmute, the Polaroids will respond again to mouse overs and clicks.


    Step 25: Creating Our Polaroid Class

    Now it’s time to create our most interesting class, our Polaroid class! For this class we’ll need the popular tweening library tweener. Download it, and save the library inside the src folder (see this guide for more details).

    
    
    package {
    	import flash.display.MovieClip;
    	import flash.events.MouseEvent;
    
    	import caurina.transitions.*;
    	import caurina.transitions.properties.*;
    	import flash.display.Bitmap;
    	import flash.events.Event;
    
    	public class Polaroid extends MovieClip {
    
    		//the scale at which the Polaroid is zoomed in
    		private static const ZOOMED_IN_SCALE:Number = 1;
    		//the scale at which the Polaroid is zoomed out
    		private static const ZOOMED_OUT_SCALE:Number = .6;
    
    		//the max height an image can be
    		private var IMAGE_MAX_HEIGHT:Number;
    		//the max width an image can be
    		private var IMAGE_MAX_WIDTH:Number;
    
    		//we must scale the loaded images, remember the scale
    		private var scale:Number;
    
    		//when we zoom out, we zoom out back to the Polaroid's original position and rotation
    		//the Polaroid's original x coordinate.
    		private var origX:Number;
    		//we also need the original y coordinate
    		private var origY:Number;
    		//store the Polaroid's original rotation
    		private var origRotation:Number;
    		//when this Boolean becomes true, the Polaroid will not respond to mouse events
    		private var muted:Boolean;
    		//we need to know if the Polaroid has been clicked
    		public var clicked:Boolean;
    
    		public function Polaroid(image:Bitmap) {
    			//make the Polaroid a button
    			buttonMode = true;
    
    			//the maximum dimensions for an image are limited by the dimensions of imageHolder
    			IMAGE_MAX_HEIGHT = imageHolder.height;
    			IMAGE_MAX_WIDTH = imageHolder.width;
    
    			//scale the Polaroid down
    			scaleX = ZOOMED_OUT_SCALE;
    			scaleY = ZOOMED_OUT_SCALE;
    
    			//we'll need to resize the image to make it fit
    			//first check if it is a portrait or landscape
    			if (image.width > image.height) {
    				//it is a landscape
    				//the scale is limited by the image's height
    				scale = IMAGE_MAX_HEIGHT / image.height;
    			} else {
    				//it is a portrait
    				//the scale is limited by the image's width
    				scale = IMAGE_MAX_WIDTH / image.width;
    			}
    
    			//scale the image
    			image.scaleX = scale;
    			image.scaleY = scale;
    
    			//add the scaled image
    			imageHolder.addChild(image);
    
    			//add event listeners to the Polaroid;
    			addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
    			addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
    			addEventListener(MouseEvent.CLICK, onClick);
    			addEventListener(Event.ADDED, whenAdded);
    		}
    
    		public function mute():void {
    			//calling this function will make the Polaroid not respond to events
    			buttonMode = false;
    			muted = true;
    		}
    
    		public function unmute():void {
    			//calling this function will make the Polaroid respond to events
    			buttonMode = true;
    			muted = false;
    		}
    
    		private function whenAdded(event:Event):void {
    			//store the Polaroid's original coordinates and rotation
    			origX = x;
    			origY = y;
    			origRotation = rotation;
    
    			//we won't need this event listener anymore, remove it
    			removeEventListener(Event.ADDED, whenAdded);
    		}
    
    		private function onMouseOver(event:MouseEvent):void {
    			//only respond if the Polaroid has not been muted
    			if (! muted) {
    				//only respond if the Polaroid has not been clicked, clicked Polaroids should not respond to mouse overs.
    				if (! clicked) {
    					//move the polaroid to the front
    					parent.setChildIndex(this, parent.numChildren - 1);
    					//move and turn the polaroid in a random direction
    					Tweener.addTween(this, {x: origX + Math.random() * 30 - 15, y: origY + Math.random() * 30 -15, rotation:origRotation + Math.random() * 20 - 10, time:1});
    				}
    			}
    		}
    
    		private function onMouseOut(event:MouseEvent):void {
    			//only respond if the Polaroid has not been muted
    			if (! muted) {
    				//only respond if the Polaroid has not been clicked
    				if (! clicked) {
    					//move the polaroid back to it's original position and rotation
    					Tweener.addTween(this, {x: origX, y:origY, rotation:origRotation, time:1});
    				}
    			}
    		}
    
    		private function onClick(event:MouseEvent):void {
    			//only respond if the Polaroid has not been muted
    			if (! muted) {
    				//if it hasn't been clicked before
    				if (! clicked) {
    					//we've been clicked, let's make that true
    					clicked = true;
    
    					//we're zooming in, let's dispatch an event (Main will pick this up)
    					dispatchEvent(new Event('zoomIn'));
    
    					//zoom the Polaroid in to the center of the stage
    					Tweener.addTween(this, {x:stage.stageWidth/2 - width/2, y:stage.stageHeight/2 - height/2, rotation:0, scaleX:ZOOMED_IN_SCALE, scaleY:ZOOMED_IN_SCALE, time: 1});
    				} else {
    					//we've already been clicked, so make clicked false
    					clicked = false;
    
    					//we're zooming out, let's dispatch an event (Main will pick this up)
    					dispatchEvent(new Event('zoomOut'));
    
    					//zoom the polaroid out, back to its original position
    					Tweener.addTween(this, {x: origX, y:origY, rotation:origRotation, scaleX: ZOOMED_OUT_SCALE, scaleY:ZOOMED_OUT_SCALE, time:1});
    				}
    			}
    		}
    	}
    }
    

    Step 26: Adding Our PolaroidHolder to Our Main Class

    Make the changes as seen in the code below.

    
    
    package {
    
    	import flash.display.MovieClip;
    
    	public class Main extends MovieClip {
    
    		//a custom class we've made which will load all images from an xml file as Bitmaps
    		private var imageLoader:ImageLoader;
    
    		private var polaroidHolder:PolaroidHolder;
    
    		public function Main():void {
    			//load our imagges
    			imageLoader = new ImageLoader();
    			imageLoader.addEventListener('imagesLoaded', displayImages, false, 0, true);
    			imageLoader.load('pictures.xml');
    		}
    
    		private function displayImages(event:Event):void {
    			//we've loaded all our images
    			polaroidHolder = new PolaroidHolder(imageLoader.polaroids);
    			addChild(polaroidHolder);
    
    			//also clean up the imageLoader
    			imageLoader.cleanUp();
    			imageLoader = null;
    		}
    	}
    }
    

    Step 27: The Result So Far

    It seems to work, but it’s not very interesting. When zooming in, the user is not “pulled in”, our product is not immersive enough. What we need is a background! By chance we created one in Step 4. Time to add our background!


    Step 28: Adding Our Background

    We had exported our background with the class Background.

    Not only will we add Background as a child of Main, we’ll also make Background darken when we’re zoomed in, and lighten when we’re zoomed out. How do we do this? Whenever a Polaroid is clicked, it dispatches a custom event, zoomIn or zoomOut. We can trace this event, just add event listeners to our Main class, they’ll pick up the zoomIn and zoomOut events, and whenever they’re picked up, we can tell our Background to lighten or darken:

    
    
    package {
    
    	import flash.display.MovieClip;
    	import flash.events.Event;
    
    	import caurina.transitions.*;
    	import caurina.transitions.properties.*;
    
    	public class Main extends MovieClip {
    
    		//a custom class we've made which will load all images from an xml file as Bitmaps
    		private var imageLoader:ImageLoader;
    
    		//this class will display all our Polaroids, by receiving a Vector of Bitmaps
    		private var polaroidHolder:PolaroidHolder;
    
    		//the wooden background, bg is an abbrivation for background
    		private var bg:Background
    
    		public function Main():void {
    			//load our images
    			imageLoader = new ImageLoader('Polaroid.swf');
    			imageLoader.addEventListener('imagesLoaded', displayImages, false, 0, true);
    			addChild(imageLoader);
    			imageLoader.load('pictures.xml');
    
    			//add our bg as a child
    			bg = new Background();
    			addChild(bg);
    
    			//add event listener, so we know when we're zoomed in or out
    			//3rd parameter of addEventListener is true, so we can capture the event, when it "bubbles" up from the Polaroid
    			addEventListener('zoomIn', onZoomIn, true);
    			addEventListener('zoomOut', onZoomOut, true);
    		}
    
    		private function displayImages(event:Event):void {
    			//we've loaded all our images
    			polaroidHolder = new PolaroidHolder(imageLoader.images);
    			addChild(polaroidHolder);
    
    			//also clean up the imageLoader
    			imageLoader.cleanUp();
    			imageLoader = null;
    		}
    
    		private function onZoomIn(event:Event):void {
    			//upon zooming in, we'll darken the bg
    			Tweener.addTween(bg, {alpha:.6, time:1});
    		}
    
    		private function onZoomOut(event:Event):void {
    			//upon zooming out, we'll lighten the bg
    			Tweener.addTween(bg, {alpha:1, time:1});
    		}
    	}
    }
    

    Step 29: Looking Back

    Tada! We’re done, this was quite a tutorial! I hope you guys had fun following this tutorial, and also learnt something from it. Why not play around with the code? You could try adding text fields and somehow display the title of the image. Or use several types of Polaroids. Thanks, and feel free to comment if you have any questions or comments. Keep an eye out for my next tutorial!


  2. Michael James Williams says:
    August 12, 2011 at 5:13 pm

    I’m neither an artist nor an animator, and yet I was able to lip-sync an audio track in next to no time, all thanks to SmartMouth by Justin Putney. This Flash Professional extension really impressed me with how quickly it was able to automate an otherwise extremely tedious task. Read on to see how it can make animating your cutscenes so much easier.


    First Impressions

    SmartMouth comes in a standard MXP package, like most Flash Professional extensions, so it was a snap to install: I just double-clicked the MXP and followed the on-screen instructions. (It’d be the same for any version of Flash from CS3 upwards, though for CS3 itself you must have installed the Extension Manager.)

    Once I installed it and restarted Flash, I could access the main panel via Commands | Lip Sync with SmartMouth:

    SmartMouth main panel

    The Help document can be brought up by clicking the question mark button; this does a great job of explaining the separate elements of the panel, but — call me biased — I felt it could also have used a brief tutorial walking me through how to use the tool. Still, there’s a detailed tutorial over on the Adobe Developer Connection, and the process is pretty simple anyway:

    First, I imported a sound track (I picked this public domain reading of one of Aesop’s Fables, from LibriVox), put it on its own layer, and set its Sync to Stream.

    Next, I created a new layer for the mouth to go on. Like I said, I’m not an artist, but fortunately we have a free Lip Sync Assets pack in the Activetuts+ archives, so I downloaded and imported that. I dragged and dropped each symbol onto a frame in my MouthShapes layer.

    Then I re-opened the SmartMouth panel; it had taken a guess at the layers I wanted to use for audio and animation, so all I had to do was choose the shapes that corresponded to each phoneme:

    SmartMouth main panel -- populated

    As you can see, it picked a Start Frame and an End Frame for me, so all I had to do was click Tell me, SmartMouth. This kicks off the audio analyzer, which plays the whole audio track through (visualizing it as it goes):

    SmartMouth Audio Analyzer

    After that, there’s a brief wait while it adds the keyframes for each mouth sound. I picked a 45 second sound file, which took up about a thousand frames (at 24fps), and SmartMouth figured out which mouth sounds went where — and actually placed the keyframes — within twenty seconds:

    SmartMouth modifies the timeline

    All I had to do then was remove the original mouth shapes from the timeline, and add a “grin” to the end (okay, technically that last one was optional). Check out the results for yourself:

    Click to start the audio and animation.

    I’m impressed!


    Room for Improvement

    I did come across a couple of bugs while using SmartMouth. When I entered my registration key, the “Success” dialog got stuck in a loop, and kept reappearing no matter how many times I hit OK. Then, later, I tried deleting all the mouth frames which SmartMouth had placed and running it again; this made it run a lot slower, and in fact it took longer than the 60 second time limit Flash imposes, making it crash without finishing its job.

    Still, neither bug was a big problem, since SmartMouth has a kind of “emergency exit”: right-click the main panel and click EXIT, and it’ll shut down, putting you back in control. Plus, if the audio is too long, you can work in chunks of a few hundred frames at a time by changing the Start and End Frame options.

    I mentioned, the Help docs are well-written — but I would have liked to see tool tips on the various buttons within the panel. It’s not immediately obvious what the buttons next to End Frame are for, nor what Mode or Limit To actually do, without reading up on them. Even “Tell me, SmartMouth” doesn’t suggest a command that will automatically place symbols in the timeline. But these are just nitpicks; once you’ve used the options, you’ll know what they do.

    My one major gripe was that, even though I placed the mouth shape symbols in different places around the stage, SmartMouth aligned them all when syncing to the audio (I think the mouth shape for the letter O is out of place in the SWF demo above). However, this proved to be my mistake: if I’d created a new symbol on the MouthShapes layer, and placed the individual mouth symbols inside that symbol, SmartMouth would have preserved my positionings.


    My Verdict

    After Ian finished Animating the Envato Community Podcast, he told me that a tool like SmartMouth would have saved him a lot of time and tedium. (Actually, he used rather more excited terms than that.) I can see why.

    In that video, there were several different people talking in turn, so there were different mouths that needed to be animated. SmartMouth doesn’t have an interface for doing this specifically, but it would be pretty simple to use it for that. Either:

    • separate the speakers’ voices into separate tracks on separate layers and run SmartMouth once per track,
    • use the Start and End Frame boxes to isolate the section of the track corresponding to one character at a time, or
    • run it once for each character and simply delete the frames that don’t match the character who’s talking.

    Although SmarthMouth’s most instantly impressive feature is its ability to put the mouth symbols on the stage in sync with the vocal track, this isn’t strictly necessary. If you prefer, you can tell SmartMouth just to create a new layer with labels corresponding to each phoneme in the vocals, so you can put the graphics in manually without having to keep scrubbing the timeline to see what sound you’re supposed to be imitating. This would be useful for frame-by-frame animation, or a scene with a lot of motion.

    It’s also possible to make SmartMouth export the phoneme data to an XML file; this could then be used in another platform, like Unity, or even loaded into a SWF with AS3 so that you could animate a custom avatar’s mouth dynamically. (From what I hear, Justin is working on a version of the tool specifically for that purpose.)

    Overall, I highly recommend SmartMouth if you need to do any lip-syncing in Flash. The basic functionality it amazing by itself, and the extra features push it over the edge.

    SmartMouth is available for purchase at the Ajar Productions website; prices start at $49.99 for a single seat, with discounts if multiple seats are bought at once.


  3. Daniel Branicki says:
    August 12, 2011 at 5:54 pm

    In this tutorial (part free, part Premium), you’ll learn how to create a 2D puzzle game in Unity which uses a Portal-style game mechanic to teleport objects across the level. In this first part, we’ll lay out the main concepts of the game, put some graphics together, and get the basic (portal-less) physics working.


    Final Result Preview

    Let’s take a look at the final result we will be working towards, across the whole of this multi-part tutorial:

    Please view the full post to see the Unity content.

    Hit the number keys 1-8 to try different levels. The aim is to get the little yellow Roly character to the designated end point, using portal mechanics. The demo shows off a few of the different mechanics we’ll introduce.

    It’s going to take us a while to get to that point, though! In this first part of the tutorial, we’ll make a good start.

    Important Note: This project does make use of a few commercial Unity plugins: Sprite Manager 2, EZ GUI, and Vectrosity. Also, while the first two parts of the tutorial are free to read, the third and fourth will be available exclusively to our Premium members.


    Step 1: Project Overview

    When creating your game you never want to jump right away into the code, first, you need an idea.

    Some people like to simply start doodling whatever they have on mind, some take a couple of random words and make a concept of the game based on thoughts that gravitate around those. Sometimes you don’t really want to make something new but rather do something that’s already done, but then again, you want to do it your way.

    Once you’ve got a pretty clear image of what you want to do, you need to be able to present your idea in a way that other people can see what the heck is this all about. Usually it takes a form of a concept art, a mock up picture, or a quick prototype. Even if you think the idea is great at the beginning, you should look objectively at those concepts and with an eye of a critic review your idea.

    If it doesn’t seem very appealing after the review, it surely won’t be later on, it’s better to simply try again with something else. If you still think it is the best game ever, you should show it to your friends, they surely won’t mind a few minutes lost, and their opinions are invaluable because they are given from other perspective than your own.

    The game we’re going to make in this tutorial is a 2D puzzle game that uses portals as its core mechanic. I’m sure you checked out the demo above so I don’t really have to explain much. I should probably show here some of my concepts for the game, but unfortunately many of them either weren’t saved or simply weren’t in digital form to begin with, I can present only a couple of them that I found lying here and there.

    The first level of the game.
    The sixth level of the game.
    The concept of the main character.

    You already know that we’re going to use Unity3D, but that’s not a very obvious choice especially if you want to make a 2D game. The main reason why I chose it is because it’s multiplatform. It can deploy a game to web browser via custom plugin, windows, mac, android, iOS, wii, and soon to xbox360 and ps3. There’s also a flash exporter in works. You may be sure that if you develop the game in unity then there are no worries about porting the game to other platforms.

    To make a 2D game we need to be able to deal with sprites, unfortunately unity doesn’t provide any built-in means to do that yet, but there are various plugins that are made specifically for this task by 3rd party developers. For this game I chose Sprite Manager 2 to serve this purpose, and EZ GUI for easy GUI creation. Aside from that, I’m also using Vectrosity to render lines and curves. I want to note that you don’t really need to use those plugins. If you have your own solution for rendering the sprites, that’s fine, but you must be prepared to fiddle with the code so you do replace what’s done with Sprite Manager 2 with the adequate code using your plugin. Also, I’m using very little of EZ GUI plugin in this tutorial, so you don’t really have to have it, but again, prepare to fiddle with the code here and there on your own. Of course the same applies to Vectrosity.


    Step 2: Create a New Project

    The first thing we need to do is to create a new project in Unity from the project wizard.

    Create new project wizard.

    Name it however you like and press Create, then the project will be created and opened. Now we should import all the the plugins so everything is on its place. The Sprite Manager 2 and EZ GUI are in .unitypackage, so all you have to do is to double click this file and then press all so all the files will be imported and then import inside the unity editor.

    Import assets wizard.

    Follow the same procedure to import the EZ GUI. For Vectrosity we need to copy the folders into our Assets folder ourselves. Navigate to both, the Assets directory in your porject folder and VectrosityScripts.zip in your Vectrosity folder. Now extract the files from VectrosityScripts.zip. In the extracted folder there should be two others: Editor and Standard Assets. Simply copy those to the Assets directory. Here’s how your project’s directories should look like for now.

    Project window shows our project tree with all the assets and folders.

    Step 3 Setup the Scene

    First thing we should do is to set the resolution of our project. Let’s say we want our game to be 480 pixels wide and 320 pixels high. In that case we need to go to the Edit->Project Settings->Player.

    That's where you can find Player Settings.

    Now in the inspector window you can see player settings. We need to change the resolution in the web player, because that’s where we’ll be deploying our game.

    I bet you know what device this resolution fits.

    As you can see there are various settings here, what interests us is the Default Screen Width and the Default Screen Height. Change them accordingly to our needs. It’s reasonable to leave Run In Background unchecked, because that will pause the game when the browser is minimazed. The game still will be running if the user marely changes tabs though.

    Now go to File->Build Settings.

    Ctrl+Shift+B is the shortcut for Build Settings.
    Unity Build Settings.

    And switch the platform to Web Player. Also remember to check Streaming, this basically allows level streaming so if someone wants to play your game, they don’t have to wait for it to load completely. You can read a bit more on this topic at the Unity Manual page on streaming.

    You need to ise the new resolution.

    Now go ahead and change the resolution in Game window from default Free Aspect to Web (480×320). Also resize this window so you can see the dark grey border around blue area, because if the window is too small to fit our web resolution then it will be resized to do so, even if we have our Web (480×320) selected. It will still keep the aspect ratio though.

    Remember that unity allows you to drag and drop every window wherever you want, so you should setup your environment the way you are comfortable with it. I’m using a bit modified 2 by 3 view, I left everything as it was except draggin the Project window below the Hierarchy.

    My unity editor layout.

    Step 4 Setup the Camera

    If you are familiar with 3D editors of any kind, you should know that the concept of pixel kind of disappears and what is introduced are standardized physics units. When it comes to length, one unit doesn’t have to be equal to one pixel, and we don’t really care about it in a 3D world, but when we are working in 2D then it’s very useful to have one pixel to one unit binding. We’ll be able to do that by tweaking the camera in our scene. First select the Main Camera object from the Hierarchy window.

    All the objects in the scene can be found in hierarchy window.

    Once you selected it, the inspector should show our camera settings. The first setting we should change is Projection. Since our game is not 3D, we don’t really need a perspective, we rather want a flat orthrographic view.

    Setting properly the camera is important for 2D game.

    Once you selected Orthographic projection, there should appear a new property called Size right below it. It basically indicates how long in world units is half of screen height. Since we want to have one to one pixel to world unit correlation, we need to set it to half of our resolution height. The width is worked out behind the scenes using the aspect ratio. Go ahead and change the default value of 100 to 160, which is our resolution height (320) divided by 2.


    Step 5 Import the First Asset

    Before we create our first sprite, we need to import the assets into unity. It’s as simple as to drag and drop the files to the project’s folder. Here is the texture we want to import for our sprite.

    Our first asset. We'll use it for quite a while.

    Remember that if you are using photoshop files in unity then you have to deal with white borders around the sprite. To solve this problem you can use a method presented in this Blurst Technology blog post or this Unity Manual page.

    To make everything clean we should create a folder for our textures. To create a folder you can simply create one in the explorer or do so directly from editor by right-clicking in the project window and then select Create->Folder.

    It's better to keep everything in folders.

    Rename the folder to Textures and drag our ball texture to it.

    If you didn’t do this yet, we should save the scene. But before that, let’s create the folder the same way we just did. This time let’s call it Scenes. Then go to File->Save Scene, navigate to our Scenes folder and save it there. Call the saved scene demo.

    Save the scene often!

    Remember to save often, it should become a habit.


    Step 6 Create a Sprite

    Let’s create our first sprite. First thing you need to do is to create a game object inside our editor. To create an object simply go to GameObject and then click on Create Empty. This will create an empty object in the scene, it will also be visible in the hierarchy window. It’s named GameObject by default.

    The base of every object.

    Let’s change the name of our object to Ball, because the first sprite will be just that, a ball. You can change the name of an object by double-clicking on it in the hierarchy window or changing it in the inspector window, it’s the first edit box on the very top of it. Now change the ball’s position to the very center of the world – change all its position components to zero. You can edit X, Y and Z position values in the Transform component attached to our sprite. After you do that, the ball’s inspector should look like this.

    Transform is a component that every GameObject possess.

    Remember that no matter how far from the camera the sprite is, it will be the same size due to camera being in orthographic mode. Nonetheless, since our camera’s z position is -10, we need to remember that our sprites need to be less than that to allow the camera capturing them. Either that, or we could change camera’s own Z position.

    Now it’s time to make use of Sprite Manager 2. Before we do that though, I would like to recommend watching the introductory videos from the developer of Sprite Manager 2. You can find them at Sprite Manager 2 page. I will guide you through the process of creating the sprite anyway, but diving into the greater details won’t hurt you. :)

    In our project window expand Plugins->Sprite Scripts, so you can see a bunch of C# scripts there. To create a sprite, we need to use either PackedSprite or Sprite script. The basic difference between those two is that the PackedSprite creates and menages the texture atlas on which sit all the frames of the sprite, while Sprite requires a premade texture atlas and a couple of additional settings for it to work. To attach the script to our ball, you can either drag and drop it on the object in the hierarchy window you want it attached to, or if you have the object selected, then drag and drop it in the inspector window or go to Component->Script->PackedSprite. Now below our Transform component, there are a couple of others with PackedSprite on top.

    We're making the first use of Sprite Manager 2 here.

    As you can see, there is a lot of things to set here. We’ll take care of it later. For now, go to the Window->Sprite Timeline.

    Here you can also edit and add animations.

    A new window should pop up. If you don’t have our ball selected, you should do that now in order to be able to work on it. You can drag the window next to our Game window so it’ll work as a tab next to it. Here’s how the window should look like.

    For now we don't have anything to display.

    As you can see, there isn’t much going on here. There is a place for Static Texture, which is basically a texture that will be displayed if the sprite won’t be animating. Let’s drag and drop our ball texture here.

    Now there's a texture that we'll use for sprite frame.

    Now let’s go back to our inspector. In order to see the sprite, it has to have positive width and height. We want our sprite to display in its original size, to achieve that, we need to check Pixel Perfect checkbox. By doing that Auto Resize is checked automatically, it makes sure that the sprite proportions are the same as the original texture.

    Remember to tick it if you want to render your sprite most accurately.

    Now we need to assign the material for our sprite. There’s a default material for sprites situated at Plugins/AnBSoft Common/Standard Material, it’s called Sprite Material. Let’s drag it from the project window on our Ball object, that’s all we need to do to assign this material to it. Now in the inspector there will be a material assigned to the sprite’s Mesh Renderer.

    We need to assign a material before we can build an atlas.

    Now it’s time to build an atlas for our sprite. To do that, we need to go to Tools->AB Software->Build Atlases.

    Alt+A if you don't like wasting those precious seconds.

    A small wizard will pop up. All settings are set to suit our needs by default, so all we need to do is to click Create.

    Build Atlases Settings are optimal by default.

    All that’s left is to press play and see how our sprite looks.

    Sprite rendered not accurately.

    As you can see, it’s far from perfect. We’ll take care of it in the next step.


    Step 7: Align the Sprite

    The issue at hand is explained at this MSDN page. We need to offset our sprite by half of the pixel to make renderer display it accurately. Let’s see if that works. let’s change our sprite’s position to (0.5, 0.5, 0.0).

    Offsetting the sprite.
    Sprite rendered accurately this time.

    As you can see, it worked well, the image displayed is now very sharp. Generally this kind of quality drop doesn’t matter for objects that move a lot. It also doesn’t matter for high resolution sprites, because then it’s unnoticable. Since our ball will be in constant movement, it won’t matter whether we align it every frame or not because the changes won’t be noticable as well. For static objects, we can align them right away in the editor and they will stay in a good shape. The problem could arise if we were dealing with low resolution sprites that are not in a constant movement. In that case we would need to align it every frame, which isn’t a huge problem at all. In fact, we’ll create a script which does that right now.


    Step 8: Create a Script

    The first thing we need to do is to create a script file. We can do that in our project window, but before we do that, let’s create a new folder and name it Game Scripts. After it’s created, you can right-click on it and then go to Create->C Sharp Script. You can rename the script by pressing F2 or clicking on its name. Name it Align.

    Align script in our Game Scripts folder.

    Everyone has their favourite script editor of choice, I’m using the one that comes with unity – MonoDevelop. It integrates with unity really well, and it’s the only one that allows for script debugging. If you use it too, I recommend to go with these preferences, which you can find under Edit->Preferences….

    Scripting tools preferences.

    Now double-click on the Align script, so it will open in our script editor.

    
    
    using UnityEngine;
    using System.Collections;
    
    public class NewBehaviourScript : MonoBehaviour {
    
    	// Use this for initialization
    	void Start () {
    
    	}
    
    	// Update is called once per frame
    	void Update () {
    
    	}
    }
    

    There’s already some code in here. When using the C# with unity, you always need those first two lines.

    
    
    using UnityEngine;
    using System.Collections;
    

    The next thing is a class declaration. In our case, we want to name it Align, so let’s change NewBehaviourScript to that.

    
    
    public class Align : MonoBehaviour {
    

    Note that everything with exception of two first lines goes inside the class. By default we’ve got two function declared here, void Update(), which is called every frame and void Start(), which is called once and that’s before the first Update() call. We don’t need the latter, so let’s remove it from the script.

    
    
    using UnityEngine;
    using System.Collections;
    
    public class Align : MonoBehaviour
    {
    
    	// Update is called once per frame
    	void Update() {
    
    	}
    }
    

    Step 9: Script the Alignment

    Alright, let’s think of how should our aligning work. Since we are going to align the position of sprite, we will need another vector to hold its true position, the way it would be unaligned. Let’s call it realPos. We need a Vector3 for holding a position, so that’s the type the realPos is going to be. You can declare class variable like this.

    
    
    public class Align : MonoBehaviour {
    
    	Vector3 realPos;
    
    	// Update is called once per frame
    	void Update() {
    
    	}
    }
    

    The next thing which we need to do is to think how will we be able to return from the aligned position to the original one. That’s pretty simple. We need to know how much we aligned it in the first place, and then unalign it. So we know that we will need to know how much alignment did take place, we need to align in both, x and y axes. A 2D vector would suffice, but since we’re working with positions in 3D space here, it would be better to keep using 3D vectors. Let’s declare another Vector3 and name it offset.

    
    
    public class Align : MonoBehaviour {
    
    	Vector3 realPos;
    	Vector3 offset;
    
    	// Update is called once per frame
    	void Update() {
    
    	}
    }
    

    Alright, it seems like everything is in place. Let’s write down our alignment code. Firstly, let’s save our original position to realPos variable.

    
    
    public class Align : MonoBehaviour {
    
    	Vector3 realPos;
    	Vector3 offset;
    
    	// Update is called once per frame
    	void Update() {
    		realPos = transform.position;
    	}
    }
    

    To get to our current position, we need to access the Transform component. In unity, you can access built-in components by simply using a reference which is always called by the name of the component. The only difference is that it doesn’t start with a capital letter. So if we want to access Transform component attached to our sprite, we can simply use transform reference for it. If we’ve got that, then all that’s left to do is to access the position vector.

    We need to calculate the offset. The offset is a difference between our original position and the aligned one. Well, we know what our position is, so we only need to calculate the aligned one. To do that we simply round the original position to integers, and then add 0.5 to that so it’s aligned properly. Now to do that in code.

    
    
    new Vector3(Mathf.Floor(realPos.x) + 0.5f, Mathf.Floor(realPos.y) + 0.5f, realPos.z);
    

    So we created new Vector3, to package our aligned position into a 3D vector. Notice that we used a math library here, you can access it whenever you need to do any math. In this case we used Mathf.Floor(), which simply returns the nearest integer lower or equal to the float value we submitted. Now we only need to substract it from the realPos, and that’s our offset!

    
    
    public class Align : MonoBehaviour {
    
    	Vector3 realPos;
    	Vector3 offset;
    
    	// Update is called once per frame
    	void Update() {
    		realPos = transform.position;
    
    		offset = realPos - new Vector3(Mathf.Floor(realPos.x) + 0.5f, Mathf.Floor(realPos.y) + 0.5f, realPos.z);
    	}
    }
    

    Now it’s a simple matter to align our position. It’s our offset substracted from realPos.

    
    
    public class Align : MonoBehaviour {
    
    	Vector3 realPos;
    	Vector3 offset;
    
    	// Update is called once per frame
    	void Update() {
    		realPos = transform.position;
    
    		offset = realPos - new Vector3(Mathf.Floor(realPos.x) + 0.5f, Mathf.Floor(realPos.y) + 0.5f, realPos.z);
    
    		transform.position = realPos - offset;
    	}
    }
    

    Remember that since we don’t want to alter the original position in any way, we need to unalign it before we start our calculations. To do that, simply add the previously substracted offset to the realPos, which is our original position.

    
    
    public class Align : MonoBehaviour {
    
    	Vector3 realPos;
    	Vector3 offset;
    
    	// Update is called once per frame
    	void Update() {
    		realPos = transform.position + offset;
    
    		offset = realPos - new Vector3(Mathf.Floor(realPos.x) + 0.5f, Mathf.Floor(realPos.y) + 0.5f, realPos.z);
    
    		transform.position = realPos - offset;
    	}
    }
    

    Finnaly, we shoud remove the constant, 0.5f and replace it with a variable, so we can align our object’s however we want, be it integers or not. Let’s declare a float and call it alignment.

    
    
    	Vector3 realPos;
    	Vector3 offset;
    	public float alignment = 0.5f;
    

    Making the variable public will allow us to change it in object’s inspector. Notice that this time we created a default value for this variable, it’s 0.5f, so if we attach our script to an object, it will have alignment equal to 0.5f by default. Let’s swap our constants with this variable.

    
    
    offset = realPos - new Vector3(Mathf.Floor(realPos.x) + alignment, Mathf.Floor(realPos.y) + alignment, realPos.z);
    

    That’s it. To check out the script simply drag and drop it from the project window on our Ball in hierarchy window. After doing so, it should be visible in the inspector window, near the bottom.

    Script is also a component.

    To test the script out, you can start the game and drag the sprite around in the scene window. You’ll see in the inspector that the position is aligned properly, and in the game window the sprite never appears to be blurry. As I stated before, this treatment wasn’t really necessary to our ball, because it will be moving constantly, but I hope that writing such a simple script served as a good introduction into scripting in unity. To remove the component, simply right-click on it in the inspector window and then select Remove Component.


    Step 10: Add Components to the Sprite

    It’s time to add some physics into the game. It’s a very simple process. The first thing we want to do is to add a Collider component. With our Ball selected go to Components->Physics->Sphere Collider.

    Radius is set automatically.

    As you should see in the editor, a green colored circle appears which represents the collider. Its size automatically fits the sprite’s mesh, so we don’t have to worry about that.

    Gizmo around the sprite.

    There is also a checkbox for Is Trigger, checking that would make our sprite a trigger, and we don’t really want that. Triggers receive a collision callback, but they are permeable. We want the ball to be a proper physical object. Now let’s attach Rigidbody. This component brings our object to life in our game world. Go to Components->Physics->Rigidbody to attach it.

    Rigidbody settings.

    We need to change a few settings here. If a Rigidbody Is Kinematic, then it’s pretty much static, no physical force can move it, the only way to change its position is to do so directly through Transform. That’s not the kind of object we want our ball to be, so we better leave that option unchecked. We want to check collisions of our ball to the Continuous Dynamic mode, by doing this the physics solver will always be detecting collisions against both, static and dynamic objects. The next thing are constraints. We don’t really want our sprite to move along z axis, nor do we want it to rotate around any other than z axis, so we’ve got to check those appropiately.

    Rigidbody settings adjusted for our needs.

    You can now hit play and should see the ball falling very slowly.

    Click here to try the demo.


    Step 11: Tweak the Physics

    The ball falls too slowly and that’s because our world unit is very small. Because we want it to be one pixel, we need to tweak the gravity so the ball falls faster. Go to Edit->Project Settings->Physics.

    Physics settings.

    After playing with it a bit, I set the gravity to -250. Another value that we should change while we tweak the physics is Min Penetration For Penalty. It’s set to 0.01 in world units, which is incredibly small value in our case. Let’s change it to one pixel.

    Physics settings adjusted for our needs.

    Click here to try the demo.


    Step 12: Create Prefabs

    The most common explanation for prefab is that it’s a blueprint of an object. It’s basic function is that if you have multiple objects of the same kind in the scene, if you want to modify them all you can modify the prefab and apply the changes to all objects at once. Every sprite needs a prefab. When generating the atlas, Sprite Manager 2 looks up which textures it will need in the current scene, and there is no way to access other scenes to see which textures they need. Creating atlases per scene is pretty much unacceptable, so what Sprite Manager 2 does is looking for prefabs in the project folder and looking up which textures they need, because prefabs are not assigned to any particular scene. This way it can build atlases that cover all of the sprites in the project.

    To create a prefab, you can right-click in the project window area and go to Create->Prefab. The next thing you need to do is to drag and drop the object which you need a prefab of from the hierarchy window on the prefab in project window.

    Prefab of our ball sprite.

    To keep everything clean, let’s create a folder named Prefabs, and throw the Ball prefab there. Note that objects that are connected to a prefab have blue font color in hierarchy window.

    Ball is now blue in the hierarchy window.

    Step 13: More Sprites

    Now it’s time to create something our ball can roll on. Here are two textures, first is for the solid ground.

    Tile for our solid ground.

    The second is for the background.

    Tile for the background.

    Now import them, preferably to Textures folder, and before you turn them into sprites, let’s clean up the project a bit more. Instead of using the same material for ball and tiles, let’s duplicate the one we already have. It’s sometimes useful to have objects that differentiate so much from each other on separate materials, because that allows you to treat them in a different way. You can duplicate any asset or object by either going to Edit->Duplicate or using a shortcut, Ctrl+D, of course the object we want to duplicate must be selected.

    Our materials inside Plugins folder.

    We should move our materials to folder exclusive for them, let’s call it Materials.

    Material moved to Materials folder

    Now create two new sprites the same way we created the first one. Remember that you need to assign Tiles Material to each of them. The sprites may look broken or not render at all right after building atlases, just hit play and everything should set up automatically.

    Ball, ground and background.

    Step 14: Ground and Background

    To make our ground tiles inpenetrable, we need to attach a Collider for them. Since our tile is basically a square, we need to attach a Box Collider instead of Sphere Collider. Go to Components->Physics->Box Collider while having our ground tile selected to attach the collider.

    Gizmo around our ground tile.

    If you move our tile below the ball and hit play, you will see that the ball doesn’t go through the ground. Note that the z value of collider’s size is 0. That’s because the mesh is basically a quad. We should change the collider’s z value to 30, so more objects with varying depth can fit on it.

    Size along Z axis should be pretty big.

    Click here to try the demo.

    Alright, let’s not forget about making every sprite into a prefab. Let’s create two new prefabs, each for one of our new sprites.

    Two other prefabs join the Ball.

    Let’s duplicate our tiles and fill the scene with them. First let’s set up the ground tiles.

    Ground laid out.

    Two rows look well. After duplicating the object so many times, the hierarchy window isn’t in a very good state.

    Lots of ground tiles in our hierarchy window.

    The solution for this is very simple. Create an empty object and drag and drop all of the platforms on it. This way, the empty object becomes the parent object of all those platforms. It basically means that if you do any actions on parent’s transform, like moving, scaling or rotating, the same action will be applied to all of its children. We can also collapse the parent, so children are invisible in the inspector.

    Parent of our tiles.

    Remember to name the parent appropiately. In our case Ground Tiles will suit it will.

    Do the same action with the background, but this time make sure that the background is actually behind both, ball and ground tiles. It would be wise to create the parent at the beginning, change its z position to something like 20 so it’s pretty far from our main plane. Make sure that childrens’ z position is equal to 0 in that case, because the parent is pretty far away already, and the parent’s position stacks on top of childrens’. If you both, children and parent would have Z position equal to 20, then in fact the childrens’ Z position in world space would be equal to 40. After you created the first child, you can duplicate and the copy will have autoamtically the same parent assigned.

    Background tiles laid out.
    Background needs to be far away.

    Step 15: More Physics Tweaking

    Drag the ball in the editor really high up, let’s say to the top of our screen and then hit play.

    Click here to try the demo.

    As you can see, the ball doesn’t bounce at all. That’s because there’s no physic material assigned to our ball, and because of that the default one is used. The default material isn’t very bouncy, and so we have to create our own. The first step would be to create a folder called Physic Materials, to keep things clean. Once you have it, right-click it and go to Create->Physic Material.

    New Physic Material.

    As you can see, there’s quite a few options to tweak here. Before we get into them though, it would be nice to change the material’s name to Ball, it’s going to be a material for our ball after all. The most interesting option for us is Bounciness. The default value is equal to 0, and that simply means that the object with this material will not bounce. We can also tweak Dynamic Friction, which is the friction applied when the object is moving and Static friction, which is the friction applied when the object stays still. Besides that, there’s also Friction Combine and Bounce Combine, which define how the material will react upon colliding with another object. You can read more on the physic materials at this Unity Reference Manual page. I played a bit with those settings, and here’s what I came up with.

    Physic material settings.

    Of course creating the material isn’t enough. We have to assign it to our ball. Simple drag and drop will do the work, but you could assign it in the Sphere Collider component attached to the ball.

    Collider with physic material.

    Hit play and see the results.

    Click here to try the demo.

    As you can see, the ball bounces properly now.


    Step 16: Approaching Portal Creation

    The general idea of a portal is that whatever enters it, it immidiately appears at another portal, so the object gets warped. Additionally, we want portals to be two-sided, so a portal has two sides which correspond to the other two of another portal. Since we grasp the general idea what do we want to do, it’s time to think of how exactly are we going to do it. As always, there are multiple options to consider. We’ll choose the one that suits us best. We should initially assume that we won’t be cutting part of an object and then change its position, because that would be a very hard thing to do.

    The easiest way to approach this problem is to create a copy of an object that goes through first portal, and this copy will be synchornized with the first one so it appears like it’s the second part of the first object.

    Two objects that seem to be one.

    Now we need to figure out how to display only a certain part of a sprite. Since we want portals to be usable from two sides, the standard trick in which we could make a ball disappear behind a wall does not come into play.

    Part of an object hides behind the wall.

    As you can see, by this method we would be able to use only one side of portal, and additionally the portals could be positioned only on the wall or the floor, so, though it’s simple, it’s not flexible at all.

    Another idea that might pop into a head while thinking about this, is to make use of render targets. It would basically mean that we would have to overlay the area of where the ball is going with a texture that was there before the ball moved into that area.

    Part of an object hides behind the texture.

    This option is not very flexible too, because we would be required to keep the area we replaced with the texture static, so nothing could move into it. Not to mention that render textures are a feature of Unity3D Pro only.


    Step 17: Hide Part of a Sprite

    What’s left for us is instead of manipulating the world so it hides part of our sprite, is to make part of a sprite disappear. There is a very nice functionality in Sprite Manager 2 that allows us to hide any part of sprite by simply declaring a rectangle in which our sprite should be visible.

    Hiding everything besides the rectangular area.

    It makes use of sprite’s ClippingRect, but it doesn’t actually define the area in which sprite is visible, but rather adjusts the UVs of the sprite to display only the pixels contained in this ClippingRect. Unfortunately, because of the way it works, it doesn’t work for rotated sprites, or to be more accurate: the sprites can be clipped correctly when unrotated. Since our warping object is a ball, this method isn’t really acceptable.

    Another way to solve this problem is to write a custom shader which would cut off part of our sprite’s texture along any axis. This way we will be able to have rotated sprite rendered properly.

    Cutom shader work.

    It will be a lot of work, but creating a shader seems like the best option for us. It will be as flexible as we will make it, so we can precisely create what do we need.


    Step 18: Create a Shader

    Let’s create a shader. You can do so by right-clicking in the project window and then goto Create->Shader. Now let’s create a folder named Shaders and put the new shader in it, you should also rename it so it makes more sense than NewShader. Cutoff will be OK.

    
    
    Shader "Cutoff" {
    	Properties {
    		_MainTex ("Base (RGB)", 2D) = "white" {}
    	}
    	SubShader {
    		Tags { "RenderType"="Opaque" }
    		LOD 200
    
    		CGPROGRAM
    		#pragma surface surf Lambert
    
    		sampler2D _MainTex;
    
    		struct Input {
    			float2 uv_MainTex;
    		};
    
    		void surf (Input IN, inout SurfaceOutput o) {
    			half4 c = tex2D (_MainTex, IN.uv_MainTex);
    			o.Albedo = c.rgb;
    			o.Alpha = c.a;
    		}
    		ENDCG
    	}
    	FallBack "Diffuse"
    }
    

    As you can see, there’s quite a lot of code here already. You can delete it whole and replace it with the following template.

    
    
    Shader "Transparent/Cutoff" {
    Properties {
    	_MainTex ("Main Texture", 2D) = "white" {}
    }
    
    Category {
    	Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
    	ZWrite Off
    	Blend SrcAlpha OneMinusSrcAlpha
    	SubShader {
            Pass  {
    
    ColorMaterial AmbientAndDiffuse
    Lighting Off
    Cull Off
    
    CGPROGRAM
    #include "UnityCG.cginc"
    #pragma vertex vert
    #pragma fragment frag
    
    sampler2D _MainTex;
    float4 _MainTex_ST;
    
    struct v2f {
        float4  pos : SV_POSITION;
        float2  uv : TEXCOORD0;
    };
    
    v2f vert (appdata_base v)
    {
    }
    
    half4 frag (v2f i) : COLOR
    {
    }
    
    ENDCG
    		}
    
    		}
    	}
    }
    

    There’s even more code here. Now, if you’re not familiar with writing shaders in unity, or even shaders in general this code must seem very unapproachable, in fact I’m not a graphics programmer and I’m not familiar with shaders at all, but with some patience if you grasp the concept then creating a simple shader like the one we are creating now is not that hard. A lot of what you see here are simple settings that you have little control of, you can see what are they about at this Unity Reference Manual page. For example Cull Off allows us to see sprites from both sides, front and back, ZWrite Off disables writing to Z Buffer, Lighting Off disables lighting and so on. There’s also a syntax specific for Shader Lab which unity uses, so if you want to know what goes where and with what, then you should really see that Unity Reference Manual page. The meat of the shader in our case is what goes between CGPROGRAM and ENDCG. Aside from that, what interests us is in the Properties{} brackets.

    Between CGPROGRAM and ENDCG we can write a custom shader in CG language. That’s all there is to it, though we need to remember here to #include "UnityCG.cginc", so we can use custom unity functionality in the shader. Another thing that we must do is to define the names of our vertex and fragment programs. To do that, we use #pragma vertex vert and #pragma fragment frag. This way the compiler will know that our vertex program is named vert and our fragment program is called frag. Next thing is sampler2D _MainTex. This is basically our texture input, the texture on which sit our sprite’s frames. Right next to it is float4 _MainTex_ST. We don’t do anything with it, we just need it defined and it can sit here, it is used to specify tiling and offset for our texture. We won’t use it directly, but as always, nothing is without purpose. The next thing is struct v2f which is basically a struct for our vertex program output and fragment program input. It contains two variables, float4 pos and float2 uv. They are containers for our vertex position ad UV respectively. Next is our vertex program. Its input is of appdata_base type, which means that it’s a vertex with position, normal and texture coordinate. It returns our output structure which we defined earlier. The last thing is our fragment program, its input is the output of the vertex shader, so it’s type is our struct v2f. It returns the COLOR, which is basically four 16-bits floats. ENDCG ends our shader.

    The properties , which go inside Properties{} brackets, allow us to submit input data directly from unity to the shader. For now we’ve got only one, _MainTex which is the texture our sprite’s frames sit on. Notice that they need to be declared here as well as in the CG shader.


    Step 19: Vertex Shader

    
    
    v2f vert (appdata_base v)
    {
        v2f o;
        o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
        o.uv = TRANSFORM_TEX (v.texcoord, _MainTex);
        return o;
    }
    

    First thing we do in our vertex shader is creating our output structure which we need to set here. To calculate the position, we simply need to multiply the position of the vertex (in object space) by UNITY_MATRIX_MVP, which is a predefined matrix. Next, we need to calculate our UV, we do that by using TRANSFORM_TEX macro. We only need to submit the texcoord from our vertex data and the the texture our sprite is using. TRANSFORM_TEX uses our _MainTex_ST, that’s why we had to define it. Finally we can return our output.


    Step 20: Fragment Shader

    In fragment shader we need it to make any pixels that go behind the axis invisible. In fact, this is the meat of our shader, here we’ll tell which texels should be displayed, and which shouldn’t. For that we need a linear equation. Linear equation can be easly used to split the sprite into two parts, and that’s all we need to do in this shader. If you forgot about how does linear equation work, you can visit this wikipedia page on linear equation. We’re going to use the standard form. So what kind of parameters does linear equation have? Those are A, B and C. The first two set the direction of the axis, and the third one only offsets the whole axis. That’s very useful, because by offsetting the whole axis we can tweak how much of the sprite should be invisible. So we need three new properties to declare, let’s call them _A, _B and _Cutoff.

    
    
    Properties {
    	_MainTex ("Main Texture", 2D) = "white" {}
    	_A ("_A", float) = 0.5
    	_B ("_B", float) = 0.5
    	_Cutoff ("_Cutoff", Range(-1.0, 1.0)) = 0.0
    }
    

    The _Cutoff is of Range type. This will give us a nice slider in editor to edit this value. Notice that its range is between -1.0 and 1.0, suggesting that the zero is minimum, and one is maximum cutoff. The first two parameters for our linear equation are normal floats, with initial value set to 0.5.

    Properties of our shader appearing in the inspector.

    Remember that we also need to define our properties in the CG program.

    
    
    sampler2D _MainTex;
    float4 _MainTex_ST;
    float _Cutoff;
    float _A;
    float _B;
    

    Alright, now let’s go back to our fragment shader.

    
    
    half4 frag (v2f i) : COLOR
    {
    
    }
    

    The first thing we should do, is to sample the appropiate color of the current pixel from the texture and assign it to our output color. Let’s name our output color c.

    
    
    half4 frag (v2f i) : COLOR
    {
    	half4 c = tex2D(_MainTex, i.uv);
    }
    

    Now, let’s check whether the pixel crosses the line from our line equation. If it’s below it, let’s change its alpha value to 0, so it will be invisible. We know our current position on the texture thanks to i.uv. It’s equal to (i.uv.x, i.uv.y).

    
    
    half4 frag (v2f i) : COLOR
    {
    	half4 c = tex2D(_MainTex, i.uv);
    
    	if (i.uv.x*_A + i.uv.y*_B < _Cutoff)
        	c.a = 0;
    }
    

    Now let’s return our color.

    
    
    half4 frag (v2f i) : COLOR
    {
    	half4 c = tex2D(_MainTex, i.uv);
    
    	if (i.uv.x*_A + i.uv.y*_B < _Cutoff)
        	c.a = 0;
    
    	return c;
    }
    

    Also, it would be nice if we allowed to tint the sprites with color of choice. Let’s create a new property called _Color.

    
    
    Properties {
    	_Color ("Main Color", Color) = (1,1,1,1)
    	_MainTex ("Main Texture", 2D) = "white" {}
    	_A ("_A", float) = 0.5
    	_B ("_B", float) = 0.5
    	_Cutoff ("_Cutoff", Range(-1.0, 1.0)) = 0.0
    }
    

    Now we need to do the same in CG..

    
    
    float4 _Color;
    sampler2D _MainTex;
    float4 _MainTex_ST;
    float _A;
    float _B;
    float _Cutoff;
    

    And multyply it with our output color in the fragment shader.

    And we're done. You can try it out and play with _A and _B parameters.

    
    
    half4 frag (v2f i) : COLOR
    {
    	half4 c = tex2D(_MainTex, i.uv);
    
    	if (i.uv.x*_A + i.uv.y*_B < _Cutoff)
        	c.a = 0;
    
    	return c*_Color;
    }
    

    That's it for the shader. You can assign it to the material by drag and drop action. Drop our shader on the Ball Material, if you want you can fiddle with factors and see how does it cut the texture. Also, if the sprite appears darker after the change of the material's shader, change Main Color to the white in the Ball Material.

    Part of the sprite is invisible.

    Now we have a lot of work to do to supply the shader with the right data. That'll come in Part 2, where we work on letting the Roly character move through a portal, hiding the part of him that's "inside" it.


  4. Michael James Williams says:
    August 12, 2011 at 6:21 pm

    From today onwards, our focus is changing. Instead of covering everything to do with Flash, Unity and Silverlight, we’ll be covering the design and development of browser-based apps and games in general. This means no more tutorials on full-Flash websites or AIR, and lots of new content on game design, UI, and HTML5. Read on to find out what we’ve got in store!


    What’s Coming Up?

    We’ve been preparing this change for a while, so we have a lot of articles planned, including:

    A 2D Unity Game With a Portal Mechanic

    Activetuts+ New Focus: Unity Game Tutorials

    Daniel Branicki has built a great little puzzle game with a Portal mechanic in Unity. In this multi-part tutorial (part Premium, part free), he’ll show you how to do the same.

    Kinect With Flash, in the Mac Web Browser

    Jonathan Reid takes his excellent guide to using augmented reality in Flash further with this Premium tutorial, explaining how you can use the Kinect controller with AS3.

    An Introduction to FlashPunk

    Daniel Sidhion shows you how to get to grips with the increasingly popular FlashPunk framework, which is designed for making Flash games and based on the Game Maker scripting language.

    Pairs, Using Photographs From Flickr

    Activetuts+ New Focus: Flash Game Tutorials

    James Tyner recreates the classic card game of Pairs, but in his version, the images all come from Flickr, based on a keyword selected by the player. A great introduction to loading data and images from an external site.

    Build a Finite State Machine in AS3

    John Reyes explains how to build a finite-state machine, which can (among many other things) be used as the basis of a game engine.

    Design a Photo Viewer App

    Activetuts+ New Focus: Browser-Based App Design Tutorials

    Daniel Apt takes you through the process of designing and animating the interface for this “Polaroid” photo viewer.

    Guide to FDT

    Michael Plank gives you a tour of FDT, an excellent development environment for Flash, showing you its unique features and explaining how to get started with it.

    Linear Kinematics

    Activetuts+ New Focus: Game Mechanics Tutorials

    Kah Shiu Chong complements his inverse kinematics tutorial with this explanation of the reverse process: linear kinematics.

    The Programmer’s Guide to UI Design

    Ashish Bogawat teaches you the basics of user interface design, so coders can create apps that look good and feel intuitive.

    Ashish will also be offering public feedback on the design of web applications, so if you’ve built one that you’d like him to critique, get in touch!

    Plus…

    We’ll also be publishing articles about:

    • Game design, including tips from professional browser game developers,
    • The geekier aspects of coding, like data structures and big O notation, and
    • HTML5 development, starting with a simple avoider game tutorial.

    If there’s anything you particularly want to see within those topics, please let us know in the comments below!


    What About the Old Tutorials?

    Don’t worry! All the tutorials we’ve published so far will remain on the site. However, we won’t be publishing any new tutorials on full-Flash website design or AIR application development.

    If you want to learn about effective website design, check out Webdesigntuts+ (it’s run by Ian Yates, who was the editor of Activetuts+ until recently). And for mobile app development, of course there’s Mobiletuts+.


    Can I Write for You?

    Send us a pitch! We’re looking for in-depth tutorials about developing browser-based apps and games, as well as articles about game design, UI and UX, and case studies of such projects you’ve worked on.

    We pay for these articles and give you full credit; see our Tutorial Submission Guidelines for more details and to find out how to submit your ideas.


  5. Michael James Williams says:
    August 12, 2011 at 6:35 pm

    Our news reporter, Joseph Labrecque, recently wrote the Flash Development for Android Cookbook, full of “recipes” for building Android applications with Flash and AIR. We’ve teamed up with Packt Publishing to give away three free copies. Read on to find out how you can win one!

    Flash Development for Android Cookbook

    From the official book description:

    • The quickest way to solve your problems with building Flash applications for Android
    • Contains a variety of recipes to demonstrate mobile Android concepts and provide a solid foundation for your ideas to grow
    • Learn from a practical set of examples how to take advantage of multitouch, geolocation, the accelerometer, and more
    • Optimize and configure your application for worldwide distribution through the Android Market
    • Part of Packt’s Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible

    How to Enter

    To enter this contest, Tweet the following message or leave a comment below explaining why you want to win the Flash Development for Android Cookbook:

    I just entered for a chance to win Flash Development for Android Cookbook from @packtpub via @envatoactive http://bit.ly/oUunLV RT to Enter

    You can click here to tweet that automatically.

    We’ll pick three lucky winners at random next week, and they’ll each receive a free copy of the ebook. Good luck!


  6. Carlos Yanez says:
    August 12, 2011 at 7:05 pm

    In this tutorial, we’ll build a really simple “keepy-uppy” game. Click the frisbee to send it skyward, then spin it with your mouse to stop it falling to the ground! Collect power-ups to change the size of the disc.

    Final Result Preview

    Let’s take a look at the final result 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 user will be able to move a character across the stage, collect upgrade items and beat gravity, you can modify the values in the class to customize the game.


    Step 2: Flash Document Settings

    Open Flash and create a 320 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.
    Most of the graphics we used have been created in previous tutorials so it won’t be necessary to include their creation.


    Step 4: Instance Names

    keepy uppy frisbee Flash game

    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, there are also two clouds clips above this graphics, they are called clouds and clouds2.


    Step 5: Tween Nano

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

    You can download TweenNano from its official website. Learn how to add it to your project here.


    Step 6: 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 7: 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 8: 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 flash.events.Event;
    import flash.net.navigateToURL;
    import flash.net.URLRequest;
    import com.greensock.TweenNano;
    import com.greensock.easing.Elastic;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    

    Step 9: 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 firsttime:Boolean = true;
    private var gravity:int = 2;
    private var throwSpeed:int;
    private var xMouse:int;
    private var xSpeed:int;
    private var topHeight:int = 40;
    private var top:Boolean;
    private var score:int = 0;
    private var scoreVal:int = 1;
    private var timer:Timer = new Timer(10000);
    private var cancelBonus:Timer = new Timer(3000);
    private var upgrade:Sprite;
    

    Step 10: 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 game. Check those functions in the next steps.

    
    
    public function Main():void
    {
    	addGameListeners();
    }
    

    Step 11: Add Listeners

    In this function we add the initial game listeners required to start the game. We also set the buttonMode property of the Frisbee to true (this will show the hand cursor when mouse over) and hide the position indicator.

    
    
    private function addGameListeners():void
    {
    	frisbee.addEventListener(MouseEvent.MOUSE_UP, launchFrisbee);
    	frisbee.buttonMode = true;
    	indicator.visible = false;
    }
    

    Step 12: Launch Frisbee

    The first move of the frisbee will activate the timers that are in charge of the upgrades and call the update function which is the principal function of the game.

    
    
    private function launchFrisbee(e:MouseEvent):void
    {
    	frisbee.removeEventListener(MouseEvent.MOUSE_UP, launchFrisbee);
    	frisbee.addEventListener(MouseEvent.MOUSE_UP, throwFrisbee);
    	stage.addEventListener(Event.ENTER_FRAME, update);
    	timer.addEventListener(TimerEvent.TIMER, showUpgrade);
    	timer.start();
    
    	xSpeed = 0;
    	xMouse = frisbee.mouseX;
    	throwSpeed = 0;
    }
    

    Step 13: Throw Frisbee

    This function resets the variables used to make the frisbee move and fall; it runs every time the frisbee is clicked.

    
    
    private function throwFrisbee(e:MouseEvent):void
    {
    	xSpeed = 0;
    	xMouse = frisbee.mouseX;
    	throwSpeed = 0;
    	top = false;
    }
    

    Step 14: Display Upgrade Bubbles

    A timed function will handle the upgrade bubbles. The timer was set in the variables declaration to have an interval of 10 seconds. The first thing to do is check for a previous bubble in screen and remove it if there is one.

    
    
    private function showUpgrade(e:TimerEvent):void
    {
    	/* Remove previous sprite */
    
    	if(upgrade != null)
    	{
    		removeChild(upgrade);
    		upgrade = null;
    	}
    

    Step 15: Double Points Upgrade

    The upgrades are bubbles that appear on screen that will give the player special abilities or enhancements.

    The following code calculates a random number (it can be 0 or 1) and instantiates the double points upgrade if the number is 0.

    
    
    var randomNumber:int = Math.floor(Math.random() * 2);
    
    if(randomNumber == 0)
    {
    	upgrade = new Double();
    	upgrade.name = 'd';
    }
    

    Step 16: Big Frisbee Upgrade

    If the calculated number is 1, the big frisbee upgrade is added to the stage. A name is given to the upgrades to determine is value when hit.

    
    
    else
    {
    	upgrade = new Big();
    	upgrade.name = 'b';
    }
    
    upgrade.x = Math.floor(Math.random() * stage.stageWidth); //give a random x position
    addChild(upgrade);
    

    Step 17: Cancel Upgrades

    Another timed function.

    This will be called when the player grabs the upgrade bubble, counting 3 seconds to end the upgrade effect.

    
    
    private function cancelUpgrade(e:TimerEvent):void
    {
    	cancelBonus.stop();
    	cancelBonus.removeEventListener(TimerEvent.TIMER, cancelUpgrade);
    
    	scoreVal = 1; //cancel double points
    	scoreTF.textColor = 0xffffff;
    	frisbee.scaleX = 1; //Return Scale to normal
    	frisbee.scaleY = 1;
    }
    

    Step 18: Update Function

    The principal function of the game, it will handle collisions with the walls, upgrades and the frisbee movement every frame. Being such an important and extensive function, we’ll take a look at it in the next part of this game tutorial.

    
    
    private function update(e:Event):void
    {
    
    }
    

    Step 19: Document Class

    keepy uppy frisbee Flash game

    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 20: Update Function

    The principal function of the game, it will handle collisions with the walls, upgrades and the frisbee movement every frame, learn how it works in the next steps.

    
    
    private final function update(e:Event):void
    {
    
    }
    

    Step 21: Move Frisbee

    The frisbee will be moved using the throwSpeed value. This value will change later in the code to make the frisbee go up, when this variable is 0, gravity will move downwards the frisbee.

    
    
    frisbee.y -= throwSpeed;
    

    Step 22: Gravity

    The following code checks if the frisbee has reached the highest point allowed, if not, the throwSpeed variable increases to make it go up. At the same time gravity is applied to the variable causing it to eventually lose its positive value and making the frisbee fall.

    
    
    if(throwSpeed >= topHeight)
    {
    	top = true;
    }
    if(throwSpeed < topHeight && !top)
    {
    	throwSpeed += 5;
    }
    
    if(throwSpeed <= 0)
    {
    	throwSpeed = 0;
    }
    
    throwSpeed -= gravity;
    frisbee.y += gravity * 3;
    

    Step 23: Click Position

    The x movement of the frisbee is calculated depending on the area the player clicks.

    
    
    if(xMouse < frisbee.width * 0.5)
    {
    	frisbee.x += xSpeed; //click the left side, so move it right
    }
    if(xMouse > frisbee.width * 0.5)
    {
    	frisbee.x -= xSpeed; //click the right side, so move it left
    }
    

    Step 24: Reduce xSpeed

    xSpeed is the value that makes the frisbee move left or right.

    This code slows this movement by subtracting its value until the maximum height is reached.

    
    
    if(xSpeed < topHeight * 0.01 && !top)
    {
    	xSpeed += 1;
    }
    
    if(xSpeed <= 0)
    {
    	xSpeed = 0;
    }
    

    Let’s stop here to make a quick test and make sure that our code is working:


    Step 25: Rotation

    To simulate the frisbee movement we rotate the a letter inside it. (This is a movie clip inside the Frisbee movie clip, which has an instance name of aLetter.)

    
    
    frisbee.aLetter.rotationZ += 50;
    

    Step 26: Score

    The score increases when the frisbee leaves the stage and by the time that it’s invisible to the player. If you click it closer to the top the score gained will be higher.

    
    
    if(frisbee.y < 0)
    {
    	score += scoreVal;
    	scoreTF.text = String(score);
    

    Step 27: Position Indicator

    This indicator follows the x position of the frisbee while it isn’t in stage.

    
    
    indicator.visible = true;
    indicator.x = frisbee.x + (frisbee.width * 0.5);
    

    Step 28: Move Background

    The next code moves the initial background (if it hasn’t been deleted) and the clouds that will be reused in the game.

    
    
    	if(bg != null){bg.y += throwSpeed;}
    	clouds.y += throwSpeed;
    	clouds2.y += throwSpeed;
    }
    

    Step 29: Delete Initial Background

    The first background will appear only at the start of the game, so it will be deleted when the player can no longer see it.

    
    
    if(bg != null && bg.y > stage.stageHeight)
    {
    	removeChild(bg);
    	bg = null;
    }
    

    Step 30: Loop Clouds

    The clouds backgrounds will appear all the time during the game duration. When a background in no longer visible, its position is reset.

    
    
    if(clouds.y > stage.stageHeight)
    {
    	clouds.y = -280;
    }
    
    if(clouds2.y > stage.stageHeight)
    {
    	clouds2.y = -280;
    }
    

    Let’s stop once again to make a quick test and make sure that we have score, indicator, rotation, looping clouds and upgrades (though they do nothing yet…) :

     


    Step 31: Double Points

    Double points are added to the score when the 2x upgrade is active, we also change the score textfield color to make the change more visible.

    
    
    if(upgrade != null && frisbee.hitTestObject(upgrade) && upgrade.name == 'd')
    {
    	removeChild(upgrade);
    	upgrade = null;
    	scoreVal = 2;
    	scoreTF.textColor = 0xf3ba35;
    
    	cancelBonus.addEventListener(TimerEvent.TIMER, cancelUpgrade);
    	cancelBonus.start();
    }
    

    Step 32: Big Frisbee

    When the player grabs the big bubble, the frisbee scale increases by 1, making it easier to click.

    
    
    if(upgrade != null && frisbee.hitTestObject(upgrade) && upgrade.name == 'b')
    {
    	removeChild(upgrade);
    	upgrade = null;
    	frisbee.scaleX = 2;
    	frisbee.scaleY = 2;
    

    Step 33: Cancel Upgrades

    The current upgrade will only be active for 3 seconds, when that time passes, its powers are cancelled.

    
    
    cancelBonus.addEventListener(TimerEvent.TIMER, cancelUpgrade);
    cancelBonus.start();
    

    Step 34: Difficulty

    The game difficulty is the gravity, this code changes the gravity based on the score. When the score reaches 100 the gravity increases by 0.5.

    
    
    if(score >= 100 && score < 102)
    {
    	gravity += 0.5;
    }
    

    Step 35: Screen Borders

    Invisible walls are used on the sides to prevent the frisbee from going offstage.

    
    
    if(frisbee.x <= 0)//Left
    {
    	frisbee.x = 0;
    }
    else if(frisbee.x >= (stage.stageWidth - frisbee.width))//Right
    {
    	frisbee.x = (stage.stageWidth - frisbee.width);
    }
    

    Step 36: Game Over

    If the frisbee falls all the way to the bottom, the game is over.

    
    
    if(frisbee.y > stage.stageHeight)
    {
    	gameOver();
    }
    

    Step 37: Remove Listeners

    The next code disables all mouse events and stops the timer, this will stop the game from performing unwanted activity.

    
    
    private final function gameOver():void
    {
    	frisbee.removeEventListener(MouseEvent.MOUSE_UP, throwFrisbee);
    	stage.removeEventListener(Event.ENTER_FRAME, update);
    	timer.stop();
    	timer.removeEventListener(TimerEvent.TIMER, showUpgrade);
    

    Step 38: Alert

    This function will stop the game and reveal the final score, it also adds a mouse listener to reset the game when clicked.

    
    
    var alert:AlertView = new AlertView();
    	alert.buttonMode = true;
    	alert.x = stage.stageWidth * 0.5;
    	alert.y = stage.stageHeight * 0.5;
    	alert.scoreTF.text = scoreTF.text + '!';
    	alert.addEventListener(MouseEvent.MOUSE_UP, restart);
    
    	addChild(alert);
    	TweenNano.from(alert, 0.7, {y: -alert.height, ease:Elastic.easeOut});
    }
    

    Step 39:Restart

    The next function will reload the swf, restarting any variable, method and returning to the first screen.

    
    
    private final function restart(e:MouseEvent):void
    {
    	navigateToURL(new URLRequest(stage.loaderInfo.url), '_level0');
    }
    

    We’re done! Try it out:


    Conclusion

    You’ve created a very entertaining game, try to add your own features and graphics.

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


  7. Eugene Potapenko says:
    August 12, 2011 at 7:35 pm

    In this post you’ll learn about a language extension called Traits, a feature of a new Beta of RASE, a smart and modern IDE for Adobe Flash based on Jetbrains MPS. Traits will allow you to use multiple inheritance in your projects, so a class can effectively extend two other classes.

    The sample project was created with ActionScript 3.0 with Traits language extension using Realaxy ActionScript Editor (RASE). If you want to do it the same way, RASE can be downloaded here (if you are new to RASE please follow the Beginners guide here)

    Why Use Multiple Inheritance?

    ActionScript is a modern object-oriented language. At the moment, actual OOP defenition and interpreting assume that multiple inheritance is a vicious practice. Thus, AS itself does not permit multiple inheritance, and only the using of interfaces provides an alternative. It’s all well and good, no need to argue.

    However, sometimes it seems unbearable. It happens that owing to this missing feature we make our code too sophisticated or even probably messy.

    For instance, we have a class Creature, which already extends Sprite. We want to teach it how to speak. "A proper OOP" imposes us to make a composition. So we need to:

    1. Create an ISpeaker interface.
    2. Add a speak() method to ISpeaker.
    3. Implement this interface with a Speaker class.
    4. The Creature class should be inherited from ISpeaker.
    5. Then add a delegate to the Creature class. The speak method would redirect calling of speak() to the delegate.
    6. Well, it’s done.

    Let’s imagine we have multiple inheritance. Then we make a Speaker class, inheriting our Creature class from the Speaker. That’s all, folks.

    Then, imagine our Creature should be able to do a lot things: to walk, to move arms and legs, to eat, to smile, to cry. Maybe also to fly. You never know what kind of requirements could become a part of the spec. As a result, we gain hundreds and thousands of lines of a “proper” OOP code, which is so redundant and verbose, that understanding its real purpose would be difficult even to its author.

    We, skilled Flashers, understand that the situation described is purely artificial. Who would create a pack of interfaces for every aspect of behavior? Even if those would be applicable not only for Creature. Indeed, the real code would look different, not so pretty and learnedly, but closer to the real world – that is to say, simpler.

    So it turns out that the best intentions of ECMAScript’s (and, later, ActionScript’s) designers to create a modern and correct OOP language accommodate badly for our everyday work.

    Enough complaining! We have a tool to fix it. RASE. Realaxy ActionScript Editor. This solution is Traits, an AS3 language extension.

    Let’s proceed to action.


    Step 1

    First, create a new project with testTraits module containing main-class Creature.

    Figure 1

    Step 2

    Enter the project details as shown here, and click Next:

    Figure 2

    Step 3

    Create a new class called Creature, in the package com.example:

    Figure 3

    Step 4

    This code should be created:

    Figure 4

    Step 5

    Import a traits language by pressing Ctrl+L (or Command+L).

    Figure 5

    Step 6

    Create a Speak interface with a single “speak” method.

    Figure 6

    Step 7

    The lower part of the window has two tabs, “Interface” and “Trait“.

    Select the “Trait” tab (colored with gray) and click on the empty editors field. A dialog box appears, offering us to create a new trait.

    Figure 7

    Step 8

    After “OK” a default implementation is created by editor. Note how this is now trait Speak rather than interface Speak:

    Figure 8

    Step 9

    Add a body to the “speak” method: just trace “Hello!” to the console.

    Figure 9

    Step 10

    In the Creature class add a “Speak” interface to “implements“.

    Figure 10

    Step 11

    The editor added an "i" to the right of the interface name. It means that the interface has a default implementation — it has trait behavior.

    Figure 11

    Step 12

    RASE recognizes such behavior and does not highlight any error when methods are added to class.

    That’s it! Our Creature can talk now! Add a call of method speak() to a class constructor to prove it.

    Figure 12

    Step 13

    Edit the run-configuration.

    Figure 13

    Step 14

    You’ll see this dialog:

    Figure 14

    Step 15

    Press the “+” button to add a new Configuration, and select ActionScript.

    Figure 15

    Step 16

    Enter the details as shown here:

    Figure 16

    (This way we can be sure we’ll see the trace.)


    Step 17

    Run the compiled SWF. A "Hello!" message appears in the console.

    Figure 17

    Here’s what we obtain:

    1. Code of interface and of implementation are bound up with navigation tools and bookmarks in editor.
    2. Code is now well-organized. Every implementation has a name: an interface name + “Impl“.
    3. Boost of the usability. In a class that uses this behavior, we only add our interface to the implemented list.
    4. Keeping apples and oranges separate. Code of Creature class is not “littered” with excessive entities. We’ve just ordered the Creature to talk.

    As a result, we have behavior that is really like multiple inheritance but stands on “proper and correct” OOP recommendations.


    Step 18

    Let’s see how it works, by looking at the code we’re actually generating.

    Click “Build->Generate (obsolete)->Generate Text from Current Model“. The newly generated code of the Creature class appears in the Output window.

    Figure 18

    The code demonstrated above implements a classical composition. The trait language extension hides redundant entities and organizes relationships between code artifacts. In fact, we operate a “pure” OOP code.

    Now we see a new fast and easy way to teach our Creature how to do everything. The main thing is the behavior: we apply the same ground rules to another classes.

    Let’s do it in 5 minutes.


    Step 19

    Add some new traits — one for each limb — just as we did before:

    Figure 19

    Step 20

    The Creature class gets now a lot of new skills, but its code remains easily-readable and clean. Without the Traits language extension it would be completely different:

    Figure 20

    It’s time to say goodbye. I’m waiting for your questions, suggestions and comments.

    Remember, if RASE is new to you, please read the “Beginners Guide“.


  8. David Appleyard says:
    August 12, 2011 at 8:14 pm

    Each month, we bring together a selection of the best tutorials and articles from across the whole Tuts+ network. Whether you’d like to read the top posts from your favourite site, or would like to start learning something completely new, this is the best place to start!


    Psdtuts+ — Photoshop Tutorials

    • Introduction to Digital Art

      Introduction to Digital Art

      Photoshop is an excellent tool for manipulating photographs but it can also be used as a means to create stunning digital art. This tutorial is part of a 25-part video tutorial series demonstrating everything you will need to know to start producing digital art in Photoshop. Digital Art for Beginners, by Adobe Certified Expert and Instructor, Martin Perhiniak will begin by teaching you how to draw in Photoshop. At the conclusion of this series you will know all you need to produce your own concept art and matte paintings in Photoshop.

      Visit Article

    • The Making of the Nutty Boat Trip

      The Making of the Nutty Boat Trip

      Most of you probably know how hard it can be to find the perfect stock images for your designs. That means you will often have to get creative and find new ways to create the perfect composition. In this tutorial, we will demonstrate how to place a couple of squirrels in a coffee mug that is floating in a body of water.

      Visit Article

    • Create a Devastating Tidal Wave in Photoshop

      Create a Devastating Tidal Wave in Photoshop

      Matte painting is a technique that filmmakers use to create backgrounds for scenes that can’t or don’t exist in real life. In the early days, matte paintings were actually painted onto glass. Today, modern filmmakers use digital applications such as Photoshop to produce the backdrops that they need. We have published many matte painting tutorials on this site meant for intermediate and advanced users. This tutorial is part of a series of tutorials that we will be publishing on this meant for those of you who may be relatively new to Photoshop or matte painting in general.

      Visit Article


    • Nettuts+ — Web Development Tutorials

    • Recently in Web Development (July Edition)

      Recently in Web Development (July Edition)

      Web development is an industry that’s in a state of constant flux with technologies and jargon changing and mutating in an endless cycle. Not to mention the sheer deluge of information one has to process everyday.

      Visit Article

    • Build your First Game with HTML5

      Build your First Game with HTML5

      HTML5 is growing up faster than anyone could have imagined. Powerful and professional solutions are already being developed…even in the gaming world! Today, you’ll make your first game using Box2D and HTML5′s canvas tag.

      Visit Article

    • Should You Start Using CSSLint?

      Should You Start Using CSSLint?

      Getting our code reviewed by a pro is a great way of improving code quality but what happens if you don’t have access to a rockstar programmer? You do the next best thing and grab a ‘lint’ for that language.

      Visit Article


    • Vectortuts+ — Illustrator Tutorials

    • Community Project: Vectortuts+ Custom Character Jam

      Community Project: Vectortuts+ Custom Character Jam

      Vectortuts+ loves Illustration and discovering new talent, so today we are proud to be launching a new community project that combines both, the Vectortuts+ Custom Character Jam. The best thing is, you can be a part of it! Find out how to get involved, at the jump.

      Visit Article

    • 13 Brandable, Free, Vector People Graphics: Mascots and Character Designs

      Brandable, Free, Vector People Graphics: Mascots and Character Designs

      Need a character or awesome vector mascot for your next design project, grab a set for free today. We’ve rounded up a collection of highly brandable vector people character packs and one off graphics. We have on display a customizable Tuts+ Guy website mascot set, creative mascot graphic pack made by Pasquale D’Silva, a top of the evolutionary ladder geek, a male and female character broken into outfits and parts – ready for animation, and more. Now’s the time to download these vector freebies, so get to it.

      Visit Article

    • Create a Marker Text Effect in Illustrator

      Create a Marker Text Effect in Illustrator

      In the following tutorial I will show you how to create a marker illustration. This tutorial involves intermediate vector shape building skills in Illustrator to create the markers, along with some layering and script usage to create the text effects. Let’s get started.

      Visit Article


    • Webdesigntuts+ — Web Design Tutorials

    • Extreme Makeover: jPaginator CSS3 Edition

      Extreme Makeover: jPaginator CSS3 Edition

      jPaginator is a nifty jQuery plugin by Remy Elazare which combines pagination and scrolling in a simple user interface. Remy recently asked me if I would like to use it for something on Webdesigntuts+ and I figured it would be a great candidate for a style make-over.

      Visit Article

    • Improving Your Productivity: Quick Tips for Photoshop

      Improving Your Productivity: Quick Tips for Photoshop

      In this exclusive web series, Adi Purdila is going to walk you through how to use a handful of web design applications to improve your productivity. Work fast, smarter, and more efficiently! Today’s session: Quick Tips for Photoshop!

      Visit Article

    • Super Simple Lightbox with CSS and jQuery

      Super Simple Lightbox with CSS and jQuery

      Rather than using a bloated plugin that has features you’ll never use, this tutorial shows you how to create a super simple lightbox for handling images. It’s perfect for image galleries, portfolios, and more!

      Visit Article


    • Phototuts+ — Photography Tutorials

    • Everything You Need to Know About Lenses: Part 1

      Everything You Need to Know About Lenses: Part 1

      So you’ve purchased your first SLR system, welcome to a new world of photography. You’ve opened Pandora’s Box to a huge range of versatility. One of the major factors that sets SLR cameras apart is their ability to change lenses. In this two-part Basix tutorial, we’re going walk your through everything you’d ever want to know about lenses.

      Visit Article

    • 10 Tips on Creative Car Photography

      Tips on Creative Car Photography

      If you’ve ever tried photographing a car, you’ll know that it’s often not as easy as first presumed. Although it can be simple enough to capture a clear and simple shot of the vehicle, it’s far more challenging to capture the design, detail and essence of the car in a photograph. To help, here are ten simple steps which will hopefully lead you through the basics of car photography.

      Visit Article

    • Understanding the Fundamentals of Camera Sensors

      Understanding the Fundamentals of Camera Sensors

      Light travels through a lens, the shutter opens, and a moment is preserved by capturing it on the camera’s sensor. This chip is an absolute essential in creating digital images. However, you may not have a good idea of how it all works. If you’re wanting to demystify the magic of how your digital SLR works, look no further than today’s Basix article all about camera sensors.

      Visit Article


    • Cgtuts+ — Computer Graphics Tutorials

    • Cgtuts+ Quiz: Know Your CG

      Cgtuts+ Quiz: Know Your CG

      Today we’re kicking off something a little different and giving you a chance to test your knowledge of all things computer graphics. This being the first ever Cgtuts+ quiz, we’re starting off fairly easy with 20 questions related to Cg in general. Will you succeed? Will you be victorious? We don’t know, but find out after the jump!

      Visit Article

    • Product Rendering With Fryrender

      Product Rendering With Fryrender

      In this tutorial by author Shaun Keenan, well look at setting up and rendering a product shot inside of RandomControls Fryrender. Shaun will start out by covering the process of setting up and preparing the scene in Maya, before exporting to Fry. Well look at creating light emitting geometry through shaders, as well as creating the jellybean and glass materials, finally well set up and tweak the render settings inside of Fry.

      Visit Article

    • Animation Reference Pack: Facial Expressions – CG Premium Content

      Animation Reference Pack: Facial Expressions – CG Premium Content

      Animating characters can be an extremely difficult task, especially without the aid of good reference materials. Today we have the second, in a series of high quality reference footage packs aimed specifically at animators. These videos are available exclusively to our premium members and are available in both 720p and 1080p high definition. Reference pack 2 contains 29 different facial expressions and a total of 116 video files!, created by regular Cgtuts+ contributors Stefan Surmabojov and Georgi Zahariev.

      Visit Article


    • Aetuts+ — After Effects Tutorials

    • “Ink-redible!” Aetuts+ Premium Ink Reveal Bundle + Tutorial

      Ink-redible!” Aetuts+ Premium Ink Reveal Bundle + Tutorial

      Today’s Premium tutorial will walk you through how use mattes to spice up your next motion graphics piece. We have an amazing download of 12 Ink Mattes and 5 Particle Mattes that were create exclusively for Tuts+ Premium members.

      Visit Article

    • Top Ten After Effects Keyboard Shortcuts – with FREE AE Starter Templates!

      Top Ten After Effects Keyboard Shortcuts – with FREE AE Starter Templates!

      These are my Top Ten Favorite After Effects Keyboard Shortcuts that I use most often to help speed up workflow…. speeding up RAM previews, purging those previews, adding keyframes to any property, previewing and scrubbing audio only… check out the video below to see them all!

      Visit Article

    • Aetuts+ Hollywood Movie Title Series -

      Aetuts+ Hollywood Movie Title Series -” Transformers – Day 1

      Todays tutorial will explain how to make the ’TRANSFORMERS 3″ flying logo style. We will start with the modeling and animation technique of the letters in Cinema 4d. Then proceed with camera movement and the construction of the interior of the “O” letter, with a hi-tech coating. We will complete with the compositing in After Effects.
      See your space! TRANSFORMERS. ;)

      Visit Article


    • Audiotuts+ — Audio & Production Tutorials

    • Quick Tip: How To Get A Clean John Frusciante Tone

      Quick Tip: How To Get A Clean John Frusciante Tone

      In this tutorial I’m going to show how to get that classic and iconic clean-Stratish tone using just modeling technology. I’m using Guitar Rig 4 to get it, but you could use whatever software or real amp, as long as it gives you a Marshall-like tone.

      Visit Article

    • How to Create the ‘Like a G6′ Bassline Sound

      How to Create the ‘Like a G6′ Bassline Sound

      If you listen to the radio, go into upscale bars, or dance at the clubs you probably have heard Far East Movement’s ‘Like a G6′. Aside from the icy vocals from the artist Dev, G6 has a very memorable bass line. If you wanted to know how to recreate that sound for a remix or to have it as a sound option in your own track then read on like a G6!

      Visit Article

    • An Introduction to ADSR

      An Introduction to ADSR

      As audio engineers we deal with ADSR everyday, even without knowing it. I certainly didn’t know what ADSR was when I first heard it, but it’s the acronym for what happens with every waveform.

      Visit Article


    • Activetuts+ — Flash, Flex & ActionScript Tutorials

    • Carve Up a Video in Real Time With AS3

      Carve Up a Video in Real Time With AS3

      Hello, code freaks! This tutorial will show you how to split a running video into blocks as if it has exploded. And all this using just ActionScript. For this tutorial we’ll use the camera as the video source, so you can see the changes live.

      Visit Article

    • Get Control of Your AS3 Event Flow With Signals

      Get Control of Your AS3 Event Flow With Signals

      In this screencast we’ll go over all you need to know about AS3 Signals – a light-weight strongly-typed alternative to the native Flash event system. Prepare to see events in a whole new way!

      Visit Article

    • Fixing Bugs in AS3: Introduction

      Fixing Bugs in AS3: Introduction

      In this tutorial, I’ll describe some of the basic information you need to debug your Flash applications. Finding and resolving errors in your ActionScript is no small task, so this is actually just the first article of a series. In this installment, we’ll take a look at some of the general things you can do to help track down your bugs.

      Visit Article


    • Wptuts+ —WordPress Tutorials

    • 8 Tips for Creating WordPress Themes That Sell

      Tips for Creating WordPress Themes That Sell

      The growing market for premium WordPress themes has made competition tougher than ever. Customers are demanding higher quality and greater functionality leaving theme developers searching for new ways to make their work stand out. Knowing what makes one theme sell better than another can be difficult, but remembering a few basic rules can make a big difference in your total sales.

      Visit Article

    • 10 Code Snippets WP Theme Developers Should Have on Speed Dial

      Code Snippets WP Theme Developers Should Have on Speed Dial

      One of the ways we endeavor to improve productivity when building WordPress templates is to have snippets of code available to us very quickly, through the use of tab-triggered shortcuts. In this article I will share with you 10 of my most-used snippets that I feel every developer should have at their fingertips.

      Visit Article

    • The Definitive Check List for Publishing Your WordPress Plugin

      The Definitive Check List for Publishing Your WordPress Plugin

      When you are getting close to completing your WordPress plugin, it’s time to start thinking about releasing it to the broader public. Getting ready for publishing a plugin requires a lot of polishing, testing and fine tuning, and it’s easy to forget some steps in the process. This tutorial will guide you through publishing the plugin in the WordPress plugin directory and work as a check list to help you make sure your plugin will be ready for the prime time by the time you hit publish.

      Visit Article


    • Mobiletuts+ — Mobile Development Tutorials

    • Android SDK: Enabling Google Analytics to Gather App Statistics

      Android SDK: Enabling Google Analytics to Gather App Statistics

      Google Analytics is a service provided by Google that makes it easy to track what users do. Recently, the Google Analytics team released an Analytics SDK for mobile platforms including Android, iOS (Apple), and mobile websites. In this tutorial, learn how to include and enable this technology within your Android projects to gather important information about how users are using your applications.

      Visit Article

    • Corona SDK: Creating a Scrolling Background

      Corona SDK: Creating a Scrolling Background

      The Corona SDK makes game development for the iPhone, iPad, and Android easy. Corona uses the Lua programming language to create cross-platform apps. In this tutorial we will explore how to create a scrolling background with the Corona SDK.

      Visit Article

    • Better Apps By Design

      Better Apps By Design

      Most mobile apps are missing that extra bit of design detail that could help them stand out from the App Store crowd. While there is no replacement for having a talented designer polish your app’s pixels for hours on end, the purpose of this series is to teach those with limited Photoshop experience and a low-to-no budget how to make apps that shine!

      Visit Article


    Thanks for Reading!

    We love bringing you the latest and greatest tutorials each month, and would like to take this opportunity to say thanks for reading, subscribing, and offering your feedback. If you have any suggestions for tutorials, or Tuts+ in general, feel free to leave them below in the comments!

    As ever, the best way to support the sites (and get your hands on superb, industry-leading tutorials) is to join our Premium program. It costs just $9 per month, and will be the best few dollars you ever spend! There’s also no risk, thanks to our 100% money-back guarantee.


  9. Joseph Labrecque says:
    August 12, 2011 at 8:58 pm

    Time for your latest fix of industry news. This week we learn about Adobe’s brand new HTML5 platform, Edge; a new resource for creative HTML5 and CSS3 demos; and a Google Chrome extension that lets you search the AS3 LiveDocs via the omnibox.

    Adobe Edge Preview Available on Labs

    Anyone who was at Adobe MAX last year will remember a prototype that was shown during the Sneaks called “Project EDGE” – which demonstrated an animation platform which targeted HTML5, JavaScript, and CSS3. Over the past few weeks, Adobe has been hinting that something would be coming down the pipeline and has released a number of short demo videos around a product called “Adobe Edge”. As of today, Adobe Edge Preview 1 is available for download on Adobe Labs (currently for free).

    Adobe Edge is a new web motion and interaction design tool that allows designers to bring animated content to websites using standards like HTML and HTML5, JavaScript and CSS. It is currently in public preview and is designed to be powerful yet approachable and easy to use. Edge Preview 1 is currently available as a complimentary download on Adobe Labs.

    Note that this is a very early build of Edge. Many public previews are planned as functionality is added to the product and its features are enhanced. Check it out and let Adobe know what you think!

    Read More on This Subject:

    • Adobe Edge on Labs
    • Adobe Edge FAQ (PDF)

    The Expressive Web (Beta)

    Adobe has also just launched a new beta resource website, called The Expressive Web. This is a project which Adobe has put together with the goal of creating both a resource and showcase that highlights some of the most creative and expressive features being added to the web today.

    In addition to highlighting and providing information on 12 new HTML5 and CSS3 features, the site itself makes extensive use of new features such as CSS3 Transitions, CSS3 Transform, Web Storage and more to provide a visually compelling resource for learning more about HTML5 and CSS3.

    Read More on This Subject:

    • The Expressive Web

    ActionScript 3.0 Search for Chrome

    For ActionScript developers, there is an interesting new add on for the Google Chrome web browser that allows AS3 LiveDocs searching through the omnibox. Pretty convenient for Chrome users!

    This extension integrates with the Chrome omnibox to bring ActionScript 3.0 standard library API autocompletion right to your fingertips. To use, type “as3″, followed by a space or tab, followed by your query.

    Read More on This Subject:

    • ActionScript 3.0 Search


  10. Michael James Williams says:
    August 12, 2011 at 9:12 pm

    Twitter and Google+ are great places to keep up to date with what’s happening with Flash and Unity, and to find excellent tips shared by other people. I’ve rounded up the most interesting posts I’ve seen from the past two weeks; if you’re not on social networks, come and take a look at what you’re missing!


    AS3 LiveDocs: Updated and Now Searchable From Chrome

    Via @tekkie and @elsassph

    The AS3 LiveDocs have been updated with a new version, containing preview content for Flash Player 11 and AIR 3.0. If you’re working with the beta versions (or just curious as to what’s new), take a look.

    In other LiveDocs news, Michael Safyan has released a Chrome extension that lets you search the AS3 LiveDocs via the omnibox (address bar). Just type ‘AS3′ in the bar, hit Tab, then type whatever you want to search and press Enter.

    LiveDocs in your omnibox

    Guide to Beginning Flash Game Development

    Via @AdobeUK

    Sam Rivello has written a wide-ranging guide on getting started with Flash platform game development. It offers a brief look at a huge number of topics: coming up with an idea, getting to grips with AS3, testing your creations, optimizing your code, monetizing what you’ve made, tracking stats, security…

    Each piece of advice has links to other articles where you can learn more about the topic. Definitely worth a read, especially if you’re new to Flash or to game development in general!


    Speed Up Your AS3 Lookups With an Unnecessary Cast

    Via Merlin Gore

    It turns out that if you replace this:

    
    
    item = items[i];
    

    …with this:

    
    
    item = items[i] as MyItem;
    

    …then you’ll speed up your lookups by a remarkable amount:

    Look up how much faster these lookups are. Hahaha.

    See Jackson Dunstan’s article for more.


    Google+ Games Are Coming

    Via John West

    SlashGear reports that Google+’s help pages mention a “Games stream” — or, rather, mentioned, since the reference has since been removed. Anyone surprised? I don’t think it’s going out on a limb to assume that Flash and Unity games will be able to interface with this.


    Adobe AIR Marketplace Will Shut Down on August 31st

    Via Joseph Labrecque

    The Adobe AIR Marketplace was launched as a place where AIR developers could sell or distribute their creations — like the App Store or Android Market, but exclusively for AIR apps. But, as Adobe explain in the recently-rewritten FAQ, the Marketplace will be shut down on August 31st.


    Chester Grant’s Advice to Young Programmers

    Via @JosephLabrecque

    A snappy list of tips for new programmers of any platform. I wouldn’t say I agree 100% with all of them, but it’s great advice as a whole. The comments are worth a read, too.

    Tip #6 has served me well:

    6. Have developer friends – This is another way to gain referrals. Eventually, your developer friend’s plate will get full, and they will need someone to pass extra jobs onto. This is where you come in. Likewise, your plate might become full, and you will need someone to pass jobs onto.

    …though there are plenty more advantages to having developer friends than gaining work referrals!


    What’s the Deal With Signals?

    Via @stray_and_ruby

    Did you see Karl Macklin’s screencast introduction to Signals that we published recently? Augment it with this article by Justin J Moses.


    Action Gameplay Flow

    Via Alec Holowka

    Not strictly to do with Flash or Unity, but relevant for game designers: great lessons on building and maintaining flow in action games, mainly influenced by Metroid Fusion:


    Calculating Dimensions of Isometric Tiles

    By Lorenzo Nuvoletta

    Lorenzo has written a useful bite-sized tip on finding the angle and side length of a tile that’s been turned into an isometric rhombus.

    I hope you like trigonometry.

    New Version of Unity

    Via Eric Heimburg

    Unity 3.4 is out! The main improvements are:

    Allegorithmic Substance Integration

    • Assign and adjust procedural textures right in the editor or at runtime
    • Stream huge levels with textures only taking up a few Kb
    • Bake to normal textures and materials for mobile devices

    Editor Improvements for More Efficient Game Development

    • User-assignable Scene View icons
    • Modifiable primitive colliders
    • Per-component gizmo collapsing

    Check out the full list here. If you’re new at Unity, check out Matt Stuttard’s Getting Started with Unity Session.


    Mochi London, August 27th-28th

    Via Merlin Gore

    This sounds like fun: a day of presentations (by developers including Iain Lobb, Merlin Gore, and Mike Jones), followed by a day hanging out at the pub with fellow Flash game creators. It’s organized by Mochi Media, and it’s free, too! More details are available here.


    Something for the Weekend: BioGems

    Via Terry Paton

    We’ll finish off with a great casual game: BioGems, which is a cross between a match-3 game and an RPG battler: match three “attack” gems to deal damage to your opponent; match three “health” gems to regain HP; and so on. The gameplay is solid and fun, the cartoon fighters are a strange mixture of adorable and deadly, and the music will be stuck in your head for hours afterwards. All in all, a fantastic casual game.

    BioGems, a great match-3 brawler.

    That’s It for Now!

    If you want to get this kind of information sooner, follow all the people mentioned above! You can also follow me on Twitter and Google+, and you can follow @envatoactive on Twitter.


Leave a Reply

Click here to cancel reply.

search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • Workshop Coding Challenge: Fix This Breakout Game
  • Enable the Latest AIR SDK in Flash Professional CS5.5+
  • Quick Tip: Versioning Your Files With Dropbox (via Webdesigntuts+)
  • Workshop: Nuclear Outrun – Critique
  • Understanding Variables, Arrays, Loops, and Null: The Post-it Note Analogy
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