Word War III – Dev Diary – 04: Tween you and me

As this slightly over the top presentation shows adding motion, bounce and wiggle to your game elements can really make a game feel rich and alive:

YouTube Preview Image

 

Luckily this is easy to achieve with the GoKit tweening library that is included with Futile. The library allows you to easily change any property of an object over a specific period of time.

For instance this bit of code:

skyline.scaleY =0.1f;
Go.to(skyline, 0.75f, new TweenConfig ().     
      floatProp("scaleY", 1.0f).
      setEaseType(EaseType.BounceOut));

Sets the skyline sprite’s y scale to 0.1, it then uses the GoKit tweening library to scale the skyline sprite’s Y scale back to 1 over a period of 750ms with an ease of  BounceOut.

The effect of this is have the skyline spring out of the ground with a nice cartoony bounce. Adding some tweens to the title screen’s sprites like this:

private void AnimateIntro()
{
    bg.y = Futile.screen.height+70;
    bg.rotation = 10f;

    Go.to(bg, 0.5f, new TweenConfig ().
        setDelay(0.5f).
        floatProp("y", 0f).
        floatProp("rotation", 0f).
        setEaseType(EaseType.BounceOut));

    skyline.scaleY =0.1f;
    Go.to(skyline, 0.75f, new TweenConfig ().
        setDelay(1.0f).
        floatProp("scaleY", 1.0f).
        setEaseType(EaseType.BounceOut));

    title.scale = 0.001f;
    Go.to(title, 0.3f, new TweenConfig ().
        setDelay(1.5f).         
        floatProp("scale", 1.0f).
        setEaseType(EaseType.SineOut));

    nuke.scaleY = 0.001f;
    Go.to(nuke, 0.5f, new TweenConfig ().
        setDelay(2.3f).         
        floatProp("scaleY", 1.0f).
        setEaseType(EaseType.BounceOut));

    startButton.scaleY = 0.0f;

    Go.to(startButton, 0.5f, new TweenConfig ().
        setDelay(3.2f).
        floatProp("scaleY", 1.0f).
        setEaseType(EaseType.BounceOut));

    helpButton.scaleY = 0.0f;

    Go.to(helpButton, 0.5f, new TweenConfig ().
        setDelay(3.3f).
        floatProp("scaleY", 1.0f).
        setEaseType(EaseType.BounceOut));
}

Along with a tween to make the buttons disappear when we tap them on the game screen, gets us this:

YouTube Preview Image

 

So how exactly do these tweens work? Well it’s all down to some clever maths. The GoKit library implements what are known as the Robert Penner equations which are a set of equations that he published in a book called Programming Macromedia Flash MX. These equations can be used to produce organic feeling motions and change.

Basically these equations all take the form of a function that takes 4 parameters:

  • t – current time unit
  • b – the starting value
  • c – the total change of the value over the duration
  • d – the duration

The simplest of these doesn’t in fact result in any easing, it simply creates a linear motion:

public float EaseNone( float t, float b, float c, float d )
{
    return c * t / d + b;
}

Plotting this out on graph gives us this (with a starting point of 0, a change of 1, over 60 frames):

The bounce out equation is a bit more interesting:

public float EaseOut(float t, float b, float c, float d)
{
    if ((t /= d) < (1 / 2.75))
    {
      return c * (7.5625f * t * t) + b;
    }
    else if (t < (2 / 2.75))
    {
      return c * (7.5625f * (t -= (1.5f / 2.75f)) * t + .75f) + b;
    }
    else if (t < (2.5 / 2.75))
    {
      return c * (7.5625f * (t -= (2.25f / 2.75f)) * t + .9375f) + b;
    }
    else
    {
      return c * (7.5625f * (t -= (2.625f / 2.75f)) * t + .984375f) + b;
    }
}

Plotting this out looks like this:

Which is a much more interesting motion.

All in all there are 31 different eases in the library. This chart shows them all:

Next up I’m going to kick things up a notch and get the basic game play in place.

Word War III – Dev Diary – 03: Some Structure

Next up is some “boring” housekeeping work on the code. Eventually the game will consist of four screens. If I keep up with my current approach of putting everything in a single script things will get pretty messy, pretty fast.

Luckily there is a better way which is highlighted in the Futile videos and in the Banana Demo project . The idea is to subclass the FContainer for each screen and then add and remove these objects from the Futile stage.

First off I create an enumeration defining each of the screens:

public enum ScreenType
{
    TitleScreen,
    GameScreen,
    ScoreScreen,
    HelpScreen
}

Then I created a base class which, extends FContainer, for my screens:

public abstract class Screen : FContainer
{       
    override public void HandleAddedToStage()
    {
        Futile.instance.SignalUpdate += Update;
        base.HandleAddedToStage();
    }

    override public void HandleRemovedFromStage()
    {
        Futile.instance.SignalUpdate -= Update;
        base.HandleRemovedFromStage();
    }

    public abstract ScreenType Type
    {
        get;
    }

    abstract public void Start();

    abstract protected void Update();
}

The Start() method will be called just after the screen object is created. This is where we will create all our FSprites etc for the screen. The Update() method is where we can stick any logic that needs to be updated every frame. I overrode HandleAddedToStage() and HandleRemovedFromStage() to clue Futile into the fact that it needs to call (or stop calling) the Update() method. Lastly I created the Type property so that the main script can figure out what type a screen is at run time.

Here is the (redacted) code for the TitleScreen:

public class TitleScreen : Screen
{
    private FButton startButton;
    private FSprite bg;
    private FSprite nuke;
    private FSprite skyline;
    private FSprite title;

    override public void Start()
    {
        bg = MakeSprite("Background.png", 0f, 0f);      
        AddChild(bg);               

        nuke = MakeSpriteWithBaseLine("nuke.png", 0f, -Futile.screen.halfHeight + 50);      
        AddChild(nuke);

        skyline = MakeSpriteWithBaseLine("skyline.png", 0f, -Futile.screen.halfHeight);     
        AddChild(skyline);      

        title = MakeSprite("Title.png", 0f, 180f);      
        AddChild(title);

        startButton = MakeButton(0f, 0f, "START");
        AddChild(startButton);      
        startButton.SignalRelease += HandleStartButtonRelease;
    }

    private FSprite MakeSprite(string name, float xPos, float yPos)
    {
        FSprite sprite = new FSprite (name);
        sprite.x = xPos;
        sprite.y = yPos;

        return sprite;
    }

    private FSprite MakeSpriteWithBaseLine(string name, float xPos, float yBaseline)
    {
        //...
    }

    private FButton MakeButton(float xPos, float yBaseline, string buttonText)
    {
        //...
    }

    public override ScreenType Type
    {
        get { return ScreenType.TitleScreen; }
    }

    override protected void Update()
    {
        // do nothing
    }

    private void HandleStartButtonRelease(FButton button)
    {
        Main.instance.GoToScreen(ScreenType.GameScreen);
    }
}

The MakeSprite(), MakeSpriteWithBaseLine() and MakeButton() methods are some helper methods to simplify the code. As you can see the Start() method is where all the components of the title screen are created. Since the title screen doesn’t have any frame based animation the Update() method is empty.

Lastly HandleStartButtonRelease() is set up as the method that is called when the start button is pressed. It calls the GoToScreen() method on the Main class to switch to the GameScreen. I’ll cover this in more detail below.

Main is a subclass of MonoBehaviour and is the script that is attached to the “Futile” object in the games’s scene. It looks something like this:

public class Main : MonoBehaviour
{
    public static Main instance;
    private Screen currentScreen = null;
    private FStage stage;

    // Initialise Futile and get the ball rolling
    void Start()
    {
        instance = this;

        FutileParams fparams = new FutileParams (true, true, false, false);

        //...

        Futile.instance.Init(fparams);

        //...

        stage = Futile.stage;       

        //...       

        // and lastly show the title screen
        GoToScreen(ScreenType.TitleScreen);
    }

    public void GoToScreen(ScreenType screenType)
    {
        if (currentScreen != null && currentScreen.Type == screenType)
        {
            return; //we're already on the same page, so don't bother doing anything
        }

        Screen screenToCreate = null;

        switch (screenType)
        {
            case ScreenType.TitleScreen:
                {
                    screenToCreate = new TitleScreen ();
                    break;
                }
            case ScreenType.GameScreen:
                {
                    screenToCreate = new GameScreen ();
                    break;
                }
        }

        if (screenToCreate != null)
        {
            //destroy the old page and create a new one
            if (currentScreen != null)
            {
                stage.RemoveChild(currentScreen);
            }

            currentScreen = screenToCreate;
            stage.AddChild(currentScreen);
            currentScreen.Start();
        }

    }

    // This is called by unity every frame
    void Update()
    {
        // check if back key was pressed
        if (Input.GetKeyDown(KeyCode.Escape))
        {           
            switch (currentScreen.Type)
            {
                case ScreenType.TitleScreen:
                    {
                        Application.Quit();
                        break;
                    }
                case ScreenType.GameScreen:
                    {
                        GoToScreen(ScreenType.TitleScreen);
                        break;
                    }
            }
        }
    }
}

The Start() method here sets up Futile, sets up a static reference to the instance of Main for easy access by the screens and lastly calls the GoToScreen(ScreenType.TitleScreen) method to get the ball rolling and show the title screen.

GoToScreen() first checks that we aren’t already on the screen that has been requested. Next up it creates an instance of new screen. If there is an existing screen it removes it from the stage (so it gets garbage collected). It then adds the new screen to the stage and calls it’s Start() method so the screen can set itself up.

One thing to note is that I currently only have the TitleScreen and GameScreen plumbed in. The switch statement will need to be expanded for the help and score screens.

Lastly the bit of code in the Update() method is there to allow the back button to work for Android. If I ever port this game to iOS I will need to add some on screen buttons to achieve the same thing.

Here is a clip of this all in action:

YouTube Preview Image

 

The next post in this series can be found here

Word War III – Dev Diary – 02: Word Smithing

So I need to find some words, more importantly I need a list of words that gradually gets more and more difficult to guess.

So what makes a word hard to guess? Doing some research on the web turns up a couple of interesting posts such as this one and this one.

It turns out that short words are harder to guess, especially ones that have “non-obvious” letters. Thus words such as “jazz”, “jug”, “by” and “gym” are much harder to guess then words such as “deployments”, “historical” or “compartmentalised”.

The list of words I have decided to use scores each word based on the relative frequencies of letters in the English language.

So “jazz” scores: j(0.153) + a(8.167) + z(0.074) = 8.394.

Whereas “deployments” scores: d(4.253) + e(12.702) + p(1.929) + l(4.025) + o(7.507) + y(1.974) + m(2.406) + n(6.749) + t(9.056) + s(6.327) = 56.928.

Lower scores indicate words that are harder to guess when you have a limited number of turns.

Letter frequency for the English language – source Wikipedia

As the blog post points out this algorithm is not perfect “cup” scores 7.469 but “gym” scores 6.396. The reality is that if “_y_” is guessed ( players often work through the vowels and then onto “Y”) there isn’t a lot of options but “gym”. However if you guess “_u_” there is quite a lot of options besides “cup”. So actually “cup” should be a harder word to guess then “gym”.

However for my purposes this list will do very nicely. Unfortunately it’s 173528 words long which is a wee bit bigger then I need :) Also my design only allows me to display words with a length of 10 characters or less so I need to cull words longer then 10 characters as well.

Enter the pig

Apache Pig is something that I have used in the past when working with “Big Data” datasets. The word list isn’t exactly Big Data but Pig will happily suit my word list mangling needs.

First off I only want words that are between 2 and 10 characters. Next I only want a sample of the 173528 words. Lastly I want the list sorted from easiest to hardest. Here is my script:

allWords = LOAD 'allscores.txt' USING PigStorage() AS (word:chararray, junk, score:float);
lessThen10 = FILTER allWords BY SIZE(word) <= 10 AND SIZE(word) > 1;
shortList = SAMPLE lessThen10 0.02;

groupAll = GROUP shortList ALL;
wordsWithMaxScore = FOREACH groupAll GENERATE FLATTEN(shortList), MAX(shortList.score) AS maxScore;

wordsWithRatio = FOREACH wordsWithMaxScore GENERATE shortList::word AS word,shortList::score AS score,
                 maxScore, (shortList::score/maxScore) AS ratio;

ordered = ORDER wordsWithRatio BY ratio DESC;
justWords = FOREACH ordered GENERATE word;

STORE ordered INTO 'wordsAndScores' USING PigStorage();
STORE justWords INTO 'words' USING PigStorage();

This produces two files, one with the words, their scores and a calculated ratio (0 to 10) based on the words score vs the maximum score in the sample list of words (wordsAndScores):

tendrilous 66.33   66.33   1.0
breathings  65.555  66.33   0.988316
rediscount  65.087  66.33   0.9812603
inoculated  64.965  66.33   0.979421
atrophies   64.735  66.33   0.9759535
stewarding  64.582  66.33   0.9736469
tailenders  64.232  66.33   0.96837026
nonethical  64.048  66.33   0.9655962
authorized  63.564  66.33   0.9582994
destroying  63.537  66.33   0.9578923

The second file (words) contains just the words:

tendrilous
breathings
rediscount
inoculated
atrophies
stewarding
tailenders
nonethical
authorized
destroying

Each file contains 2477 words sampled out of the original list of 173k words.

I was initial going to use the ratio to group blocks of similar difficulty words together but have abandoned this idea. The plan is now to simply step through the list in random increments which will have the effect of gradually increasing the difficulty of the words during a game but not result into too many words repeating between games.

One problem with the list is that it contains words that are not in common usage for example “tendrilous” (adjective for “tendril”, a specialized threadlike leaf or stem that attaches climbing plants to a support by twining or adhering) and “kohlrabies” (plural of “kohlrabi”, A cabbage of a variety with an edible turnip like swollen stem). So I will need to manually groom the list at some stage :)

Loading the word list

Loading the word list in Unity is pretty straight forward. Firstly I copy the file into my project’s resource folder and name it words.txt, next I use the following code to load the words into a string list:

List words;

void LoadWordList()
{
    words = new List ();
    StringReader reader = null;

    TextAsset words = (TextAsset)Resources.Load("words", typeof(TextAsset));

    reader = new StringReader (words.text);
    if (reader == null)
    {
        Debug.Log("words.txt not found or not readable");
    } else
    {
        string txt;

        // Read each line from the file
        while ((txt = reader.ReadLine()) != null)
        {
            words.Add(txt);
        }
    }

    Debug.Log("Loaded " + words.Count + " words");
}

With the word list in place, I think I will next focus on getting the game’s screen flows sorted. Onwards and upwards!

_Update: _Click here for the next post in this series

Word War III – Dev Diary – 01: Getting started

So I’ve decided to knuckle down and build AND actually release a game. I read somewhere (probably Reddit) that publishing a development diary really helps on the motivation front. It sounds like a good idea so here we are :-)

Some constraints

First off to narrow my focus I have decided that:

  • I will make a 2D game. My 3D modeling is OK but it takes a loooong time.
  • My target is a mobile app. So distribution is taken care off.
  • Android is my initial platform: I already have test devices and dev platforms
  • I’m going to use the Unity3D platform. I bought the Android and iOS platform licenses a while back so I should really use them. Also its a very nice cross-platform tool.

Time

Nothing kills a side project like the distractions of everyday life. Luckily Mrs Gremlin suggested a few weeks ago that I earmark Monday nights for doing some game development. I’m taking her up on her offer. My wife is the best!

but Unity isn’t 2D…

No it isn’t but it handles lots of polygons which when textured and put on a plane equals lots of GPU accelerated sprites.

After digging around I found Futile. It’s new, has zero documentation but the intro videos and sample code looked good.

YouTube Preview Image

 

The developer also set up a Futile sub-reddit and he is very active on it. So I decided to give it a go.

I knocked together a shell of a space invader game using these neat graphics. Futile appears to do exactly what it says on the tin and it seems intuitive to use. Here is a short clip of my test project:

YouTube Preview Image

 

The pitch

Ok now for the elevator pitch:

The game is hangman with a time limit rather then guess limit. When a player guesses a word they are presented with a new one. The words the player gets to guess get progressively harder as the game goes one. The game has a time limit of 120 seconds with a progress bar incrementing towards game over every second. Each correct letter guess reduces the bar by 2 seconds. Each failed guess adds 1 second. Completing a word knocks off 10 seconds.

The game has a nuclear armageddon theme. The progress bar is broken up into DEFCON levels 5 to 1. The game is named “Word War III”.

Kick off

First up I sketched out some screen flows and layout ideas. Things like high score tables etc can come later:

Mrs Gremlin offered to build a title page for me (using Illustrator) and I knocked up the game page to test out the layout of the letter keys. I’m normally create game graphics using Inkscape which is vector based, this allows graphics to be easily scaled and resized as things develop. Here is the title page and the game page layout test:

The fonts are Passion One and Hand of Sean. Unfortunately it looks like the license for Hand of Sean has recently changed and it is no longer free so I’ll need to find a replacement for it.

Using BMFont I created some font atlases and then used TexturePacker (I bought the Pro version) to pack all the assets into the following atlas:

One issue I had is that I failed to export the font images as 32bit images. This caused all sorts of weirdness when TexturePacker created the atlas.

Also Futile spat the dummy when tring to load the smaller of the font sets. Some array index out of bounds error that I haven’t had time to track down.

Next I got down to some actual coding using the FSprite, FLabel and FButton classes I created the game screen. Testing on a actually device showed that my buttons were too small. Mrs Gremlin also pointed out that the keys should laid out in a QWERTY fashion. Some more tweaking and I ended up with this:

YouTube Preview Image

Not a bad start for a few hours of work.

Update: Click here for the next post in this series

Did Microsoft just kill Flash? IE10 won’t run Flash unless your site is on a Microsoft whitelist!

Yeah you read that right. I just received an interesting email from Brightcove (the video delivery guys) about issues with their Flash based solution and Windows 8 running the new Internet Explorer 10. To quote:

We wanted to make you aware of a development with Microsoft around Windows 8 that may affect your video content delivered through Brightcove Video Cloud.

Background

Microsoft is expected to release the next version of Windows, Windows 8, on October 26th. With Windows 8, Microsoft has made a decision to limit the use of Flash as a means for delivering content and move toward a concept of a plug-in free experience in Internet Explorer 10. As a result, sites will not be allowed to serve Flash in Internet Explorer 10 unless they have been given prior approval and have been whitelisted by Microsoft.

What this means for you

The default browser experience in the new Windows UI will not allow Flash unless the site has been approved and granted access by Microsoft. Therefore, if a Brightcove Video Cloud customer is looking for a full featured playback experience that is on par with Windows 7 today, they will need to submit a request to Microsoft in order to be whitelisted.

My initial reaction was “surely not???” and a quick search of the web indicates that there is a great deal of confusion as to what the IE10 behavior will actually be. However the Brightcove email provides an link to a handy Microsoft support article which clears things up.

Basically:

  1. Windows 8 ships with two (!) versions of Internet Explorer 10. One for the desktop experience and one for the Windows UI experience.
  2. Both ship with a built in version of Flash BUT the Windows UI version won’t run Flash unless your site is on a whitelist. The Desktop version will run Flash as normal.
  3. You can add a meta tag to your pages which will trigger a prompt to the user to run your site in the desktop IE if they visit it using the Windows UI version of IE (a lovely user experience… not)
  4. Lastly they give details on how you get you site added to the whitelist (basically emailing Microsoft with the details of your site and details of how it conforms to Microsoft’s Flash Content Guidelines)

Buried in the support article is the following reasoning for the difference in behavior between the Desktop and Windows UI IE version’s Flash support:

While any site can play Flash content in Internet Explorer 10 for the desktop, only sites that are on the Compatibility View (CV) list for Flash can play Flash content within Internet Explorer 10 in the the new Windows UI. We place sites with Flash content on the CV list if doing so delivers the best user experience in Internet Explorer 10 with those sites. For example, how responsive is the content to touch? Does it work well with the onscreen keyboard, or affect battery life? Do visual prompts comply with the Windows Store app user experience guidelines? Sites that rely on capabilities (for example, rollover events and peer-to-peer (P2P) functionality) that are not supported within Windows UX guidelines for Windows Store apps, and don’t degrade gracefully in their absence, are better off running in Internet Explorer 10 for the desktop with Flash.

Which seems fair enough but kinda underscores the point that having the Windows UI on the desktop version of Windows 8 (and making it the default) doesn’t really make sense when you consider what the user will be doing when they sit down at a PC to work.

It will be interesting to see if Windows 8 lands with a splash or a thud on October 26. I suspect it might be a thud and a whimper. Certainly it looks like Flash and the web are going to be in for a rough ride.

 

My Romo has arrived

imageMy Romo smartphone robot turned up yesterday! Romo is the brain child of a couple of guys in Las Vegas and the result of a pretty sucessful Kickstarter project (the first I have ever contributed to).

Romo is a simple tracked bot, about 15cm long, which charges via USB. What makes the Romo very cool, is the fact that it’s brains is your smartphone!

The Romo connects via the headphones jack to your smartphone and it accepts commands via short bursts of sound, created by the apps you run on your phone. The commands sound like short chirps.

Currently an app is available for iOS and Android devices, which lets you remote control your Romo. For this to work, you need two devices, one plugged into the Romo as its brain and other that acts as a remote control. Communicating via Wifi, you can drive your Romo around, get a video feed of what the Romo is looking at (via the attached smartphone’s camera) , take pictures and change the Romo’s expression with accompanying sound effects.

Unfortunately the Android app running on my Nexus One and Acer Iconia A500 does not seem to work :-( My Nexus produced no movement at all and the A500 only sporadically turned on the one track. This caused a bit of panic as I thought that my Romo was defective but I then connected it to an iPhone (using an iPod Touch as the remote) and everything worked fine.

Hopefully future releases of the Android app will fix my problems (the app was only released a few days ago).

However for me, the most exciting thing about the Romo is the fact that it has a full SDK that lets you write your own apps. This makes the Romo particularly suitable as an affordable robotics platform. Currently the iOS SDK is available on github, the Android SDK is due for release “any day now”.

If you are interested in the communications protocol check out this file and this file from the iOS SDK (no protocol docs have been released by Romotive yet).

If you want your own Romo you can get one here.

Tutorial: Creating your first Unity Android App

This tutorial is out of date. See here for an updated tutorial covering the latest version of Unity.

This is a quick, step by step guide to creating a simple spinning cube app for Android using Unity. This tutorial is for windows but other then the install instructions it should work for other platforms. By the end of this tutorial you will have created an app that displays a red spinning cube on a blue background on your Android device.

Setup Unity

You will need Unity AND the Android feature to create the app. Unity basic is free and the Android feature is currently free till the 8th April 2012 (which saves you $400). Download the installer from here and get your license from here.

Install Unity and register it using your license key which should have been emailed to you.

Setup the Android SDK

To create an Android app you need to install the Android SDK, which can be downloaded from here. I have the SDK installed to c:\android-sdk-windows

Once the SDK is installed you need to add the Android 2.1 (API level 7) package. Run the SDK Manager and use it to download the API level 7 packages. See here for more info.

Lastly, you will need to install the USB device drivers for your Android device. Whilst it is possible to use the Android Emulator its performance is pretty bad (especially when emulating tablets) so you are much better off testing on a real device. If you are using a “Nexus” device you can install USB drivers using the SDK Manager, otherwise search the web for your devices drivers.

To test that everything is set up, plugin in your device, open a cmd prompt and run the following commands :

cd \android-sdk-windows\platform-tools
adb devices

Your plugged in device should be listed. You may have to enable USB debugging for your device. Go to Settings -> Applications -> Development and turn on USB debugging.

Creating the app

Start Unity and select File -> New Project to create a new project, name the project RedCube.

In the drop-down box in the upper right of the screen make sure 4 Split is selected.

Create the cube

From the GameObject menu select Create Other and then select Cube. Make sure that Cube is selected in the Hierarchy panel (3rd panel along the top of the screen), then in the Inspector panel (far right panel) set the following values for the cube:

  • Position: x = 0, y = 0, z = 0
  • Rotation: x = 0, y = 45, z = 45
  • Scale: x = 2, y = 2, z = 2

Position the camera

Select the Main Camera  in the Hierarchy panel and set the following properties for the camera in the Inspector panel:

  • Position: x = 0, y = 0, z = -5

Add a light

From the GameObject menu, select _Create Other _and then Point light. Set the following properties for the light:

  • Position: x = 0, y = 0, z = -5

Test the scene

Click on the Play button (top center of the screen). You should now see the lower left panel switch to the Game tab and you should see a white cube on a blue background.

Press the Play button again to stop the game.

Note this important! Unity allows you to make changes whilst the game is running but these changes are lost as soon as you stop the game running. This is great for debugging but is an easy way to lose you changes :)

Save your project

Speaking of losing your work, now is a good time to save your project. Select File -> Save Scene, enter RedCubeScene as the name for the scene when prompted. Then select File -> Save Project to save the project. Remember to save your work regularly.

Making the cube red

Right click in the Project panel (3rd along the bottom) and then select Create -> Material, name it RedMat. In the Inspector window click on the white color block next to Main Color and then select a red color from the color picker. Drag the RedMat material from the Project window onto Cube  in the Hierarchy window. The cube should now turn red in the various scene windows.

Making the cube spin

In Unity scripts are used to add behavious to objects and to create the logic of your game. We will use a script to make the cube spin.

Right click in the Project panel and select Create -> C# Script, name it Spin.

In the Inspector window click the Open button, give it a moment for the MonoDevelop IDE to launch. You should see a code editor window. Modify the code to read as follows:

using UnityEngine;
using System.Collections;

public class Spin : MonoBehaviour {
    // Use this for initialization
    void Start () {
    }

    // Update is called once per frame
    void Update () {
        // rotate at 90 degrees per second
        transform.Rotate(Vector3.up * Time.deltaTime*90);
    }
}

Save the code (press Ctrl+S) and then switch back to the Unity editor.

Drag the Spin script from the Project window on to Cube in the Hierachy window.

Press the Play button. You should now see a red cube spinning in the Game window. Press Play again to stop the game.

Building the app

Now that we have the app completed, we need to build it.

Select Edit -> Project Settings -> Player

In the Inspector window under the Per-Platform Settings click on the tab with the Android icon (3rd tab along).

In the Other Settings section change the following values:

  • Bundle Identifier = com.rabidgremlin.tut.redcube
  • Minimum API Level = Android 2.1 ‘Eclair’ (API Level 7)

Now, select File -> Preferences and then select the External Tools section. Click on the button next to Android SDK location and select the root folder of your Android SDK install (c:\android-sdk-windows in my case).

Next plug-in your device.

Now, select File -> Build & Run, this will open the Build Settings window. Select  Android under platform and then click on the Build & Run button, when prompted for a name for the .apk file enter in RedCube.

A build dialog will pop up and you will see the app being built, then you will see a message about the app getting pushed to your device.

Have a look at your device, you should see the RedCube app starting up, followed by a red cube spinning on a blue background.

Congratulations you have created your first Unity Android app !

What next?

First off go and complete the 3D platform game tutorial. This will give you a good understanding of how Unity works. Also check out the very comprehensive documentation and the very helpful community.

Now go nuts :)

Update: If you are interested in creating 2D games with Unity check out my Dev Diary for my game Word War III

Building a modern web app, some learnings

I recently built a fairly rich web application from the ground up. Whilst I’ve being building web apps since the mid-nineties this little project had a different flavour to it and I thought I’d go over my learnings here.

Firstly why was this project different:

  • its a Facebook app and uses their JavaScript SDK. This means that 99% of the app runs client side with only a small bit of server side code.
  • I’m was the sole developer. Normally I work with 2 or more other developers, focus on the back-end work and leave the bulk of front-end stuff to others
  • rapid development approach. The app was built quickly with me working closely with a UX guy and a designer. Whilst the functionality was locked down early on, the user interface and interactions evolved rapidly and iteratively.

First observation: its so easy

OK that is slightly facetious, but modern CSS and JavaScript frameworks mean that you don’t have to be guru to build nice looking, smooth functioning, cross browser applications.

For this application I used the Twitter Bootstrap CSS framework and the jQuery Javascript framework.

Get a designer

Yes I know I just said that it’s easy and you don’t need to be a guru to create nice looking apps BUT whilst Twitter Bootstrap encapsulates a great design, you are still going to want to customise it.

Designers have the knack of adding the odd image, drop shadow or bit of whitespace that can make a perfectly ok looking web page just suddenly pop. Not to mention the selection of color a palettes and general pixel pushing.

On a similar front having a UX guy on hand is invaluable. If you don’t have one, then read Steve Krug’s Don’t Make Me Think book and then go and find yourself a UX guy  :) 

Facebook

The Facebook API is now pretty mature and is very stable (compared to the last time I used it a few years ago).

One annoying things is that the calls that you make to explore the user’s social graph (via the FB.api function) are very low-level and the data is returned in a callback. This can make your code very messy, since you often have to chain your app’s logic in the callback function, if your app needs data before it can proceed. For example:

FB.api('/me', function(response) {
  // do something with response here
  // make next api call (with nested callback) here
});

Additionally if you need to, for instance, retrieve friend profile data you can land up making hundreds of calls:

// grab all my friends
FB.api('/me/friends', function(response) {

    $.each(response.data, function(index, value) {
       // get profile for each friend (this triggers another HTTPS call)
       FB.api('/' + value.id , function(profile) {
         // do something with profile data
       });
    });

});

Luckily there is a better way, the FB.query and FB.waitFor functions. These let you run queries against a user’s data using a SQL like language (FQL) and then block waiting for the response. This greatly reduces the time it takes to retrieve data and keeps your apps logic a bit simpler:

var query = FB.Data.query('SELECT uid,name,current_location FROM user WHERE uid IN (SELECT uid1 FROM friend WHERE uid2=me())');
query.wait(function(rows) {
    $.each(rows, function(index, value) {
       // do something with friend data here
    });
});
// rest of app logic continues here

Firebug

Get it (hopefully this isn’t news to you). This tool is invaluable for web development. It allows you to debug JavaScript, view the DOM, check network traffic and tweak CSS in browser.

It’s also a good idea to test you app in different browsers as you go. During this app’s build I had FireFox, Chrome and IE 8 all running so I could see that everything was working. Luckily by using Twitter Bootstrap and jQuery I had no cross-browser issues at all other then the fact that IE didn’t get nice round corners.

Make sure it validates

The W3C provides a tool for validating web pages. It’s always good to be sure that your pages validate, not just because it is good practice but because it stops browsers from entering their “quirks mode” which often causes odd and quirky behavior.

The Web Developer plugin for Firefox provides a handle shortcut for submitting your local HTML to the W3C validator.

In my case everything validated except for the Facebook namespace declaration and the custom Facebook tags such as fb:like. Whilst there are ways around this I decided on not been too purist.

HTML5

Try use HTML5 for your app. It works very nicely. For IE browsers (before 9.0) use the HTML5 shim to get some HTML5 support.

However Twitter Bootstrap does not support IE6, so I used this trick to make any IE6 browsers redirect the user to a “browser unsupported” page with tips on how to upgrade their browser. In the __section add the following comment:

 <!--[if lt IE 7]><script type="text/javascript">window.location = 'notsupported.html';</script><![endif]-->

This uses the conditional comments feature of Internet Explorer to redirect IE6 browsers to the notsupported.html page, other browsers will simply treat it as a HTML comment.

Improving load times

It is best practice to load all the CSS files in the section of the page and all the JavaScript files at the end of the page (just before the </body> tag). This makes the page feel much more responsive as the browser can start to render and layout the page before everything is loaded.

Having said that, a complex web app tends to pull in a lot of CSS and JavaScript files and minimizing the number of objects that are fetched from the server is a key factor in having a speedy app.

Ideally you only want your app to load a single CSS file and a single Javascript file. To achieve this in my app I concatenate the CSS files and JavaScript files (in the correct order) and then compress them using Yahoo’s YUI compressor.

Since I wanted this to be a repeatable process I used Ant to create a build script to do this. Firstly the concatenation:

<concat destfile="${tmp.dir}/all.js">
  <fileset file="${www.dir}/jquery.min.js" />
  <fileset file="${www.dir}/jquery-ui-1.8.16.custom.min.js" />
  <fileset file="${www.dir}/jquery.masonry.min.js" />
  <fileset file="${www.dir}/bootstrap-modal.js" />
  <fileset file="${www.dir}/bootstrap-twipsy.js" />
  <fileset file="${www.dir}/bootstrap-alerts.js" />
  <fileset file="${www.dir}/app.js" />
</concat>

And then the compression:

<exec executable="java">
  <arg value="-jar"/>
  <arg value="yuicompressor-2.4.7.jar"/>
  <arg value="${tmp.dir}/all.js"/>
  <arg value="-o"/>
  <arg value="${tmp.dir}/all.js"/>
</exec>

Now during development you don’t want to be dealing with concatenated and compressed files so my PHP pages contain a snippet like this:

<?php
if ($config['mode'] != 'prod')
{
?>
    <script src="jquery.min.js"></script>
    <script src="jquery-ui-1.8.16.custom.min.js"></script>
    <script src="jquery.masonry.min.js"></script>
    <script src="bootstrap-modal.js"></script>
    <script src="bootstrap-twipsy.js"></script>
    <script src="bootstrap-alerts.js"></script>
    <script src="app.js"></script>
<?php
}
else
{
?>
    <script src="all.js?@buildtimestamp@"</script>
<?php
}
?>
</body>

With mode getting set in my app’s config file.

Of course there are a ton of other things you can do to tune your app. Get the YSlow addon for Firebug and run the report on your pages to see what can be done.

Cache busting

Ant can also very helpfully update parts of your files whilst copying them around. This can be used to burn in all sorts of things, like version numbers and build timestamps. It can also be used create a effective cache buster when a new version of your app is released….

Firstly you need to set up an Ant property with an appropriate value:

<tstamp>
  <format property="buildtimestamp" pattern="yyyyMMddHHmmssSSS" locale="en,UK"/>
</tstamp>

Then in your HTML you can append @buildtimestamp@ following to file references:

<link rel="stylesheet" href="all.css?@buildtimestamp@"/>
...
<script src="all.js?@buildtimestamp@"></script>

Then lastly apply a filter in Ant when you are copying the files around:

<copy todir="${tmp.dir}">
  <fileset dir="${www.dir}">
    <include name="**/*.php" />
  </fileset>
  <filterset>
    <filter token="mode" value="prod" />
    <filter token="release" value="${rel}" />
    <filter token="buildtimestamp" value="${buildtimestamp}" />
    <filter token="builddate" value="${builddate}" />
  </filterset>
</copy>

PHP config file

To keep things nice and clean, I created a config.php file looking like this:

<?php if ( ! defined('CONFPATH')) exit('No direct script access allowed');

// set this to '@' + 'mode' + '@' during development so that style sheets and javascript files are individually included (see index.php)
// ant build scripts will replace this at build time
$config['mode'] = '@mode@'

?>

Then in my other PHP files I pulled in the config file using:

<?php
   define('CONFPATH','config.php');
   require_once CONFPATH;
?>

As you can see from the comments and the Ant snippets above, I overwrite the mode value with _‘prod’_ during my Ant build process to ensure that my compressed .js and .css files are used.

Miscellaneous files

Finally make sure you add a favicon and a robots.txt to avoid annoying 404 webserver logs. For fun why not add a humans.txt too.

Summary

Well that pretty much covers it. Hopefully there are one or two new  ideas here that you can use in your apps. Feel free to post any questions in the comments section below.

Help Stop SOPA

Please help stop SOPA by completing this form! If you aren’t in the USA click on the “Not In US” option at the bottom of the form.

SOPA is a new US law that is getting voted on in the next few days, it will fundamently affect the way the Internet works and it will therefore directly affect you!

Want to know more about SOAP ? Checkout this infographic or this video

AnimfxNZ 2011 – day 3

[oops I totally forgot to post this sooner!]

Day 3 of the conference was spent at Park Rd post productions for Weta’s digital day. This was awesome.

The first part of the day was largely focused on Rise of the Planet of the Apes and the latter half on the new Adventures of Tintin movie.

Chris White (VFX Supervisor) covered the huge amount of research and work that went into creating the digital apes for the movie.

Matt Muntean (Lead Creature TD) and Sonya Teich (Creature TD) discussed the technologies and techniques used to create the apes. I was fascinated to see how much was actually simulated rather then modelled. The apes had anatomically correct skeletons on top of which muscle and fat layers where simulated so that the skin could be correctly simulated. On top of that the skin itself was simulated in multiple layers with fat underneath to get skin wrinkles and movement on the face correct. The hair, cloth and water simulation was equally impressive.

Peter Hillman (Developer) discussed their deep compositing techniques using deep images (images that effectively contain Z data for each pixel) which allows various rendered layers to be easily composited ( and recomposited) together really quickly. The use of the properties of these deep images to easily composite life action plates with CG was simple but inspired.

Erik Winquist (VFX Supervisor) covered in depth the GoldenGate Bridge scene in the movie. This 11 minute scene had over 250 VFX shots and included outdoor motion capture covering a massive space. It was very interesting to see how all the parts and work fitted together to produce the final outcome.

YouTube Preview Image

Wayne Stables (VFX Supervisor) covered the building of the world of Tintin. The amount of research (down to how rusty hinges on doors look in the middle east) was staggering. The footage of the performance capture sets with the wire mesh props (to avoid occulding the motion tracking markers) and virtual cameras for the directors was very interesting.

Jamie Beard (Previs & Animation supervisor) discussed how previs was used to explore the look and feel of the film. It was really interesting to see how gags the previs team created, wound up in the final film. What was really interesting was the postvis work. Since the scenes were all performance captured, the team was able to go back and rework the virtual cameras to come up with interesting shots and cuts. In all Jamie said the project took 5 years! Performance capture was completed in 30 days.

YouTube Preview Image

After the talks a small group of us got taken on a short behind the scenes tour. We got to see the sound production and foly areas. The sound mixing area was particularly impressive. Imagine an entire theater filled up with a couple of plush seats and a giant 10m wide mixing desk (404 channels). The theater is actually a room within a room, floating on shock absorbing springs to keep the sound contained. The group was walked through the sound layers of a scene from District 9 and we then got to see the big action scene of the movie with the sound cranked up to 11. When the alien ship activated and blew its horn the entire room shook!

Next it was the foley room. It was filled with the most unbelievable junk, old bicycles, car doors, pots, gravel, straw, stone, bit of woods etc. I reckon my 3 year old would think he was in heaven if he got into there :)

As with the other days of the conference day 3 was very interesting and a lot of fun.