logo
468x60-2-495


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

Review: SmartMouth for Flash Makes Lip-Syncing Simple

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.



View full post on Activetuts+

banner ad

10 Responses to “Review: SmartMouth for Flash Makes Lip-Syncing Simple”

  1. Michael James Williams says:
    August 11, 2011 at 1:01 am

    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.


  2. Daniel Branicki says:
    August 11, 2011 at 1:31 am

    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.


  3. Michael James Williams says:
    August 11, 2011 at 2:21 am

    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.


  4. Michael James Williams says:
    August 11, 2011 at 2:59 am

    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!


  5. Carlos Yanez says:
    August 11, 2011 at 3:24 am

    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!


  6. Eugene Potapenko says:
    August 11, 2011 at 3:58 am

    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“.


  7. David Appleyard says:
    August 11, 2011 at 4:11 am

    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.


  8. Joseph Labrecque says:
    August 11, 2011 at 4:32 am

    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


  9. Michael James Williams says:
    August 11, 2011 at 5:25 am

    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.


  10. Kah Shiu Chong says:
    August 11, 2011 at 5:27 am

    Imagine a chain of particles animating in symphony together: A train moving as all attached compartments follow suit; a puppet dancing as its master pulls its string; even your arms, when your parents hold your hands as they lead you in an evening walk. Movevment ripples down from the last node to the origin, abiding to constraints as it goes. This is inverse kinematics (IK), a mathematical algorithm that calculates necessary motions. Here, we’ll use it to create a snake that’s a little more advanced than the one from Nokia games.


    Final Result Preview

    Let's take a look at the final result we will be working towards. Press and hold UP, LEFT and RIGHT keys to make it move.


    Step 1: Relationships in a Chain

    A chain is constructed of nodes. Each node represents a point in the chain where translation and rotation may happen. In IK chain, motion ripples down in reverse from the last node (last child) to the first node (root node) as opposed to Forward Kinematics (FK) where kinematics traverse from the root node to the last child.

    All chains begins with the root node. This root node is the acting parent unto which a new child node is attached. In turn, this first child will parent the second child in the chain, and this is repeated until the last child is added. The animation below depicts such a relationship.


    Step 2: Remembering Relationships

    The IKshape class implements the notion of a node in our chain. Instances of IKshape class remember their parent and child nodes, with the exceptions of the root node which has no parent node and the last node which has no child node. Below are the private properties of the IKshape.

    
    
    private var childNode:IKshape;
    private var parentNode:IKshape;
    private var vec2Parent:Vector2D;
    

    Accessors of these properties are shown as below:

    
    
    public function set IKchild(childSprite:IKshape):void
    {
    	childNode = childSprite;
    }
    
    public function get IKchild ():IKshape
    {
    	return childNode
    }
    
    public function set IKparent(parentSprite:IKshape):void
    {
    	parentNode = parentSprite;
    }
    
    public function get IKparent():IKshape
    {
    	return parentNode;
    }
    

    Step 3: Vector from Child to Parent

    You may notice that this class does store a Vector2D that points from child node to parent node. The rationale for this direction is due to motion flowing from child to parent. Vector2D is used because the magnitude and direction of vector pointing from child to parent will be manipulated frequently while implementing behaviour of an IK chain. Thus, keeping track of such data is necessary. Below are methods to maniplate vector quantities for IKshape.

    
    
    public function calcVec2Parent():void
    {
    	var xlength:Number = parentNode.x - this.x;
    	var ylength:Number = parentNode.y - this.y;
    
    	vec2Parent = new Vector2D(xlength, ylength);
    }
    
    public function setVec2Parent(vec:Vector2D):void
    {
    	vec2Parent = vec.duplicate();
    }
    
    public function getVec2Parent():Vector2D
    {
    	return vec2Parent.duplicate();
    }
    
    public function getAng2Parent():Number
    {
    	return vec2Parent.getAngle();
    }
    

    Step 4: Drawing Node

    Last but not least, we need a method to draw our shape. We shall draw a rectangle to represent each node. However, any other preferences can be put in by overriding the draw method here. Iv included an example of a class overriding the default draw method, the Ball class. (A quick switch between shapes will be demonstrated at the end of this tutorial.) With this, we complete the creation of the Ikshape class.

    
    
    protected function draw():void
    {
    	var col:Number = 0x00FF00;
    	var w:Number = 50;
    	var h:Number = 10;
    	graphics.beginFill(col);
    	graphics.drawRect(-w/2, -h/2, w, h);
    	graphics.endFill();
    }
    

    Step 5: The IK Chain

    IKine class implements behaviour of an IK chain. Explanation regarding this class follows this order

    1. Introduction to private variables in this class.
    2. Basic methods used in this class.
    3. Mathematical explanation on the workings of specific functions.
    4. Implementation of those specific functions.

    Step 6: The Data in a Chain

    Code below shows the IKine class private variables.

    
    
    private var IKineChain:Vector.<IKshape>;		//members of chain
    
    //Data structure for constraints
    private var constraintDistance:Vector.<Number>;		//distance between nodes
    private var constraintRangeStart:Vector.<Number>;	//start of rotational freedom
    private var constraintRangeEnd:Vector.<Number>;		//end of rotational freedom
    

    Step 7: Instantiate the Chain

    IKine chain will store a Sprite datatype that remembers the relationship of its parent and child. These sprites are instances of IKshape. The resultant chain sees the root node at index 0, the next child at index 1, … until the last child in sequential manner. However, construction of chain is not from root to last child; it is from last child to root.

    Assuming that the chain is of length n, construction follows this sequence: n-th node, (n-1)-th node, (n-2)-th node … 0-th node. The animation below depicts this sequence.

    Upon instantiation of IK chain, the last node is inserted. Parent nodes will be appended later. The last node appended is the root. The code below are methods of IK chain construction, appending and removing nodes to chain.

    
    
    public function IKine (lastChild:IKshape, distance:Number)
    {
    	//initiate all private variables
    	IKineChain = new Vector.<IKshape>();
    	constraintDistance = new Vector.<Number>();
    	constraintRangeStart = new Vector.<Number>();
    	constraintRangeEnd = new Vector.<Number>();
    
    	//Set constraints
    	this.IKineChain[0] = lastChild;
    	this.constraintDistance[0] = distance;
    	this.constraintRangeStart[0] = 0;
    	this.constraintRangeEnd[0] = 0;
    }
    
    /*Methods to manipulate IK chain
    */
    public function appendNode(nodeNext:IKshape, distance:Number = 60, angleStart:Number = -1*Math.PI, angleEnd:Number = Math.PI):void
    {
    	this.IKineChain.unshift(nodeNext);
    	this.constraintDistance.unshift(distance);
    	this.constraintRangeStart.unshift(angleStart);
    	this.constraintRangeEnd.unshift(angleEnd);
    }
    
    public function removeNode(node:Number):void
    {
    	this.IKineChain.splice(node, 1);
    	this.constraintDistance.splice(node, 1);
    	this.constraintRangeStart.splice(node, 1);
    	this.constraintRangeEnd.splice(node, 1);
    }
    

    Step 8: Getting Chain Nodes

    These following methods are used to retrieve nodes from the chain whenever there's a need.

    
    
    public function getRootNode():IKshape
    {
    	return this.IKineChain[0];
    }
    
    public function getLastNode():IKshape
    {
    	return this.IKineChain[IKineChain.length - 1];
    }
    
    public function getNode(node:Number):IKshape
    {
    	return this.IKineChain[node];
    }
    

    Step 9: Constraints

    We have seen how the chain of nodes is being represented in an array: Root node at index 0, … (n-1)-th node at index (n-2), n-th node at index (n-1), n being length of chain. We can conveniently arrange our constraints in such order as well. Constraints come in two forms: distance between nodes and degree of bending freedom between nodes.

    Distance to maintain between nodes is recognised as a child node's constraint upon its parent. For the sake of referencing convenience, we can store this value as constraintDistance array with index similar to that of the child node's. Note that the root node has no parent. However, distance constraint should be registered upon appending the root node so that if the chain is extended later, the newly-appended "parent" of this root node can utilise its data.

    Next, the angle of bending for a parent node is restricted to a range. We shall store the start and end point for range in constraintRangeStart and ConstraintRangeEnd array. Figure below shows a child node in green and two parent nodes in blue. Only the node marked "OK" is allowed because it lies within the angle constraint. We can use similar approach in referencing values in these arrays. Note again that root node's angle constraints should be registered even though not in use due to similar rationale as previous. Plus, angle constraints does not apply to the last child because we want flexibility in control.

    All constraints drawn onto this diagram.

    Step 10: Constraints: Getting and Setting

    The methods as follow may prove useful when you have initiated constraints on a node but would like to alter the value in future.

    
    
    /*Manipulating corresponding constraints
    */
    public function getDistance(node:Number):Number
    {
    	return this.constraintDistance[node];
    }
    
    public function setDistance(newDistance:Number, node:Number):void
    {
    	this.constraintDistance[node] = newDistance;
    }
    
    public function getAngleStart(node:Number):Number
    {
    	return this.constraintRangeStart[node];
    }
    
    public function setAngleStart(newAngleStart:Number, node:Number):void
    {
    	this.constraintRangeStart[node] = newAngleStart;
    }
    
    public function getAngleRange(node:Number):Number
    {
    	return this.constraintRangeEnd[node];
    }
    
    public function setAngleRange(newAngleRange:Number, node:Number):void
    {
    	this.constraintRangeEnd[node] = newAngleRange;
    }
    

    Step 11: Length Constraint, Concept

     The following animation shows the calculation of length constraint.


    Step 12: Length Constraint, Formula

    In this step, we'll have a look at commands in a method that help to constrain distance between nodes. Note the highlighted lines. You may notice only the last child is applied this constraint. Well, as far as the command goes, this is true. Parent nodes are required to fulfill not only length but angle constraints. All these are handled with the implementation of method vecWithinRange(). Last child need not be constrained in angle because we need maximum bend flexibility.

    
    
    private function updateParentPosition():void
    {
    	for (var i:uint = IKineChain.length - 1; i > 0; i--)
    	{
    		IKineChain[i].calcVec2Parent();
    		var vec:Vector2D;
    
    		//handling the last child
    		if ( i == IKineChain.length - 1)
    		{
    			var ang:Number = IKineChain[i].getAng2Parent();
    			vec = new Vector2D(0, 0);
    			vec.redefine(this.constraintDistance[IKineChain.length - 1], ang);
    		}
    		else
    		{
    			vec = this.vecWithinRange(i);
    		}
    
    		IKineChain[i].setVec2Parent(vec);
    		IKineChain[i].IKparent.x = IKineChain[i].x + IKineChain[i].getVec2Parent().x;
    		IKineChain[i].IKparent.y = IKineChain[i].y + IKineChain[i].getVec2Parent().y;
    	}
    }
    

    Step 13: Angle Constraint, Concept

    First, we calculate the current angle sandwiched between the two vectors, vec1 and vec2. If the angle is not within the constrained range, assign the minimum or maximum limit to the angle. Once an angle is defined, we can calculate a vector that is rotated from vec1 together with the constraint of distance (magnitude).

    Angle sandwiched between two vectors.

     The following animation offers another alternative to visualising the idea.


    Step 14: Angle Constraint, Formula

    The implementation of the angle constraints is as below.

    
    
    private function vecWithinRange(currentNode:Number):Vector2D
    {
    	//getting the appropriate vectors
    	var child2Me:Vector2D = IKineChain[currentNode].IKchild.getVec2Parent();
    	var me2Parent:Vector2D = IKineChain[currentNode].getVec2Parent();
    
    	//Implement angle bounds limitation
    	var currentAng:Number = child2Me.angleBetween(me2Parent);
    	var currentStart:Number = this.constraintRangeStart[currentNode];
    	var currentEnd:Number = this.constraintRangeEnd[currentNode];
    	var limitedAng:Number = Math2.implementBound(currentStart, currentEnd, currentAng);
    
    	//Implement distance limitation
    	child2Me.setMagnitude(this.constraintDistance[currentNode]);
    	child2Me.rotate(limitedAng);
    
    	return child2Me
    }
    

    Step 15: Angle with Directions

    Perhaps it is worthy to go through here the idea of getting an angle that interprets clockwise and counter-clockwise direction. The angle sandwiched between two vectors, say vec1 and vec2, can be easily obtained from the dot product of those two vectors. The output will be the shortest angle to rotate vec1 to vec2. However, there is no notion of direction as the answer is always positive. Therefore modification on the regular output should be done. Before outputing the angle, I used vector product between vec1 and vec2 to determine whether the current sequence is positive or negative rotation and incorporated the sign into the angle. I have highlighted the directional feature in lines of code below.

    
    
    public function vectorProduct(vec2:Vector2D):Number
    {
    	return this.vec_x * vec2.y - this.vec_y * vec2.x;
    }
    
    public function angleBetween(vec2:Vector2D):Number
    {
    	var angle:Number = Math.acos(this.normalise().dotProduct(vec2.normalise()));
    
    	var vec1:Vector2D = this.duplicate();
    	if (vec1.vectorProduct(vec2) < 0)
    	{
    		angle *= -1;
    	}
    
    	return angle;
    }
    

    Step 16: Orienting Nodes

    Nodes that are boxes needs to be oriented to the direction of their vectors so that they look nice. Otherwise, you will see a chain like below. (Use the arrow keys to move.)

    The function below implements the right orientation of nodes.

    
    
    private function updateOrientation():void
    {
    	for (var i:uint = 0; i < IKineChain.length - 1; i++)
    	{
    		var orientation:Number = IKineChain[i].IKchild.getVec2Parent().getAngle();
    
    		IKineChain[i].rotation = Math2.degreeOf(orientation);
    	}
    }
    

    Step 17: Last Bit

    Now that everything is set, we can animate our chain using animate(). This is a composite function making calls to updateParentPosition() and updateOrientation(). However before that can be achieved, we have to update relationships on all nodes. We make a call to updateRelationships(). Again, updateRelationships() is a composite function making calls to defineParent() and defineChild(). This is done once and whenever there's a change in the chain structure, eg nodes are added or dropped at runtime.


    Step 18: Essential Methods in IKine

    In order to make IKine class work for you, these are the few methods you should look into. I’ve documented them in a table form.

    Method Input Parameters Role
    IKine() lastChild: IKshape, distance:Number Constructor.
    appendNode() nodeNext:IKshape, [distance:Number, angleStart:Number, angleEnd:Number] add nodes to chain, define constraints implemented by node.
    updateRelationships() None Update parent-child relationships for all nodes.
    animate() None Recalculating the position of all nodes in chain. Must be called every frame.

    Note that angle inputs are in radians not degrees.


    Step 19: Creating a Snake

    Now lets create a project in FlashDevelop. In the src folder you will see Main.as. This is the sequence of tasks you should do:

    1. Initiate copies of IKshape or classes that extend from IKshape on the stage.
    2. Initiate IKine and use it to chain up copies of IKshape on stage.
    3. Update relationships on all nodes in chain.
    4. Implement user controls.
    5. Animate!

    Step 20: Draw Objects

    Object is drawn as we construct IKshape. This is done in a loop. Note if you'd like to change the outlook of the drawing to a circle, enable comment on line 56 and disable comment on line 57. (You’ll need to download my source files in order for this to work.)

    
    
    private function drawObjects():void
    {
    	for (var i:uint = 0; i < totalNodes; i++) {
    
    	var currentObj:IKshape = new IKshape();
    	//var currentObj:Ball = new Ball();
    	currentObj.name = &quot;b&quot; + i;
    	addChild(currentObj);
    	}
    }
    

    Step 21: Initialise Chain

    Before initialising the IKine class to construct the chain, private variables of Main.as are created.

    
    
    private var currentChain:IKine;
    private var lastNode:IKshape;
    private var totalNodes:uint = 10;
    

    For the case here, all nodes are constrained to a distance of 40 between nodes.

    
    
    private function initChain():void
    {
    	this.lastNode = this.getChildByName(&quot;b&quot; + (totalNodes - 1)) as IKshape;
    	currentChain = new IKine(lastNode, 40);
    
    	for (var i:uint = 2; i <= totalNodes; i++)
    	{
    		currentChain.appendNode(this.getChildByName(&quot;b&quot; + (totalNodes - i)) as IKshape, 40, Math2.radianOf(-30), Math2.radianOf(30));
    	}
    	currentChain.updateRelationships();
    
    	//center snake on the stage.
    	currentChain.getLastNode().x = stage.stageWidth / 2;
    	currentChain.getLastNode().y = stage.stageHeight /2
    }
    

    Step 22: Add Keyboard Controls

    Next, we declare variables to be utilised by our keyboard control.

    
    
    private var leadingVec:Vector2D;
    private var currentMagnitude:Number = 0;
    private var currentAngle:Number = 0;
    
    private var increaseAng:Number = 5;
    private var increaseMag:Number = 1;
    private var decreaseMag:Number = 0.8;
    private var capMag:Number = 10;
    
    private var pressedUp:Boolean = false;
    private var pressedLeft:Boolean = false;
    private var pressedRight:Boolean = false;
    

    Attach onto stage the main loop and keyboard listeners. I’ve highlighted them.

    
    
    private function init(e:Event = null):void
    {
    	removeEventListener(Event.ADDED_TO_STAGE, init);
    	// entry point
    
    	this.drawObjects();
    	this.initChain();
    	leadingVec = new Vector2D(0, 0);
    
    	stage.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
    	stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
    	stage.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp);
    }
    

    Write the listeners.

    
    
    private function handleEnterFrame(e:Event):void
    {
    	if (pressedUp == true)
    	{
    		currentMagnitude += increaseMag;
    		currentMagnitude = Math.min(currentMagnitude, capMag);
    	}
    	else
    	{
    		currentMagnitude *= decreaseMag;
    	}
    
    	if (pressedLeft == true)
    	{
    		currentAngle -= Math2.radianOf(increaseAng);
    	}
    
    	if (pressedRight == true)
    	{
    	currentAngle += Math2.radianOf(increaseAng);
    	}
    
    	leadingVec.redefine(currentMagnitude, currentAngle);
    	var futureX:Number = leadingVec.x + lastNode.x;
    	var futureY:Number = leadingVec.y + lastNode.y;
    
    	futureX = Math2.implementBound(0, stage.stageWidth, futureX);
    	futureY = Math2.implementBound(0, stage.stageHeight, futureY);
    
    	lastNode.x = futureX;
    	lastNode.y = futureY;
    	lastNode.rotation = Math2.degreeOf(leadingVec.getAngle());
    
    	currentChain.animate();
    }
    
    private function handleKeyDown(e:KeyboardEvent):void
    {
    	if (e.keyCode == Keyboard.UP)
    	{
    		pressedUp = true;
    	}
    
    	if (e.keyCode == Keyboard.LEFT)
    	{
    		pressedLeft = true;
    	}
    	else if (e.keyCode == Keyboard.RIGHT)
    	{
    		pressedRight = true;
    	}
    }
    
    private function handleKeyUp(e:KeyboardEvent):void
    {
    	if (e.keyCode == Keyboard.UP)
    	{
    		pressedUp = false;
    	}
    
    	if (e.keyCode == Keyboard.LEFT)
    	{
    		pressedLeft = false;
    	}
    	else if (e.keyCode == Keyboard.RIGHT)
    	{
    		pressedRight = false;
    	}
    }
    

    Notice that I’ve used a Vector2D instance to lead the snake moving around the stage. I’ve also constrained this vector within the boundary of stage so it will not move out. The Actionscript performing this constraint is highlighted.


    Step 23: Animate!

    Press Ctrl+Enter to see your snake animate!. Control its movement using the arrow keys.


    Conclusion

    This tutorial does require some knowledge in Vector Analysis. For readers who would like to get a familiar look at vectors, do have a read on the post by Daniel Sidhon. Hope this helps you in understanding and implementing inverse kinematics. Thanks for the read. Do drop suggestions and comments as Im always eager to hear from audiences. Terima Kasih.


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