Tweens & Jugglers: Animating Your Stage

A little late, but hey! better than never ;-) , we will have a look at the linchpin of Sparrow’s animating powers: Tweening.

What’s a Tween, you ask? Let’s have a look at Wikipedia: It tells us that tweening is “the process of generating intermediate frames between two images to give the appearance that the first image evolves smoothly into the second image. Inbetweens are the drawings between the key frames which help to create the illusion of motion.”

That’s about right for Sparrow too. Like e.g. in Flash/ActionScript Sparrow allows you to smoothly transition the (numerical) properties of your stage objects from an initial value N to a final value M in time X.

Tweening Object Properties

Let’s go with a simple real-world example: Imagine a nice little stage containing a blast door that is going to be shut.

For those of you who need a background story: “It’s Oct-13 in 2043. Ruth Lezz, your 25-year old female main character and down-and-dirty mercenary, just intentionally overheated the central nuclear power core of the first human colony on Mars. The automated disaster containment sub-routine of the station’s master control program requires all blast doors to be shut down immediately in order to minimize station personnel casualty numbers.” Knock yourself out! ;-)

What we are going to do is animate the closing of the blast door:

  //Create a door of the blast persuasion.
  //The initial Y value is -440 which means that the door is wide
  //open. (We are going to see 40px of the door.)
  BlastDoor *blastDoor = [[BlastDoor alloc] initWithY:-440];
  [self addChild:blastDoor];

  //Create the corresponding tween and feed him the door object,
  //state the time it takes to close and the final value for Y.
  //In our case this is 0, since we want the door to shut
  //completely.
  SPTween *tween = [SPTween tweenWithTarget:blastDoor
    time:4.0f transition:SP_TRANSITION_LINEAR];
  //Delay the tween for two seconds, so that we can see the
  //change in scenery.
  [tween setDelay:2.0f];
  //Tell the tween that it should transition the Y value to 0.
  [tween animateProperty:@"y" targetValue:0];

  //Register the tween at the nearest juggler.
  //(We will come back to jugglers later.)
  [self.stage.juggler addObject:tween];

…aaand that’s it! We now have an animated blast door that moves (closes) from Y=-440 to Y=0 in 4.0 seconds. Cool, right? But wait, it gets better!

Transition Types

Sparrow offers a variety of transition types which you can use for your tweens. A transition type defines the way the object properties value will travel from N to M, in our case from -440 to 0. Typically you will start with a linear transition (SP_TRANSITION_LINEAR) and your property value will travel from -440 to 0 in a straight fashion. There are, however, some other cool transition types that help adding fun to your animations. Here is a chart of the other currently available transition types:

Sparrow's transition types

For our blast door example it makes sense to let the door fall down from the ceiling instead of slowly lowering it to the floor. So instead of using SP_TRANSITION_LINEAR we are going to do this:

  //Change the transition type to an ease-out-bounce and
  //adjust the tween duration to fit our needs.
  SPTween *tween = [SPTween tweenWithTarget:securityDoor
    time:1.5f transition:SP_TRANSITION_EASE_OUT_BOUNCE];

  //Leave the rest of the code as is.

Alright! The door finally slams into the ground as one would expect it to. It feels way heavier now and heavier means more secure. We achieved that by changing only two variables of our code.

But what if Ruth Lezz needs to get off the station, hacks into the security system and stops the doors from closing? Read on…

Canceling A Tween

Sometimes it may be necessary to cancel a tween while it is already in its tweening phase. There are three ways to achieve that:

  1. You can keep track of your SPTween object and remove it from its juggler when the time has come.
  2. You can remove all tweens of a certain object.
  3. Or you can stop the whole juggler from executing any more tweens.

We are going to use the second option and stop all tweens targeting the door as soon as Ruth Lezz has successfully hacked into the security system:

- (void) closeTheDoor {
  //Create the tween.
  SPTween *tween = [SPTween tweenWithTarget:securityDoor
    time:1.5f transition:SP_TRANSITION_EASE_OUT_BOUNCE];
  [tween animateProperty:@"y" targetValue:0];
  [self.stage.juggler addObject:tween];
}

//This method gets called when Ruth Lezz has hacked the
//security system.
- (void) onSecuritySystemHacked {
  //Remove the tween when the time has come.
  [self.stage.juggler removeTweensWithTarget:securityDoor];
}

So what we did is react to the players actions and stop the blast door from closing as soon as the security system got hacked. That’s enough for today. Keep in touch, because there is going to be more on tweens and jugglers soon!

Soon To Come

  • Jugglers: What are jugglers and how to use them elegantly?
  • The Stage Juggler: What is the stage juggler?
  • Delaying Invocations: How am i supposed to delay method calls?
del.icio.us Digg StumbleUpon Google Twitter Facebook
3 Comments

Multitasking

As you all know, one of the most important new features of iOS 4 is multitasking. I just found out that the scaffold and demo projects I provided with Sparrow 0.9 had problems with multitasking — and this might be similar in your existing Sparrow projects.

Fortunately, the fix is extremely simple. All you have to do is open your application delegate (ApplicationDelegate.m) and update the contents of the following methods:

- (void)applicationWillResignActive:(UIApplication *)application
{
    [sparrowView stop];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [sparrowView start];
}

That’s it! Now your app should support multitasking.

I updated the Sparrow download package, so that the demo and scaffold projects use this code, too. I also included a small update of the atlas generator, so if you are using it, you can fetch that, too.

del.icio.us Digg StumbleUpon Google Twitter Facebook
0 Comments

How to make HD games with Sparrow

Before the release of the iPhone 4, developers were in the comforting situation that all iPhones had the same screen resolution (unlike Android developers, which have to support many kinds of displays). Now, with the arrival of the iPhone 4, there are two screen resolutions that can be targeted: 480×320 and 960×640.

Fortunately, Apple did the best to make that transition as painless as possible. It’s no coincidence that the new resolution is exactly twice the old resolution — that way, old applications simply use 4 pixels on the iPhone 4 for what was one pixel on previous devices, and look just like before.

New applications, however, can profit from the higher resolution. If you create all graphics in the high resolution from the start, the additional effort is minimal — if you follow the steps I show below.

BTW, the tools I am using throughout this tutorial are part of Sparrow — but that does not mean that you cannot use them with other game engines (like Cocos2D) or pure UIKit applications. The texture atlas generator, for example, can easily be modified so that it produces a different output format.

What we want to achieve

Sparrow’s demo application was created in the way I am describing in this tutorial. Start up the demo application in the iPhone simulator to see the result. When the simulator appears, select “Hardware – Device – iPhone 4″ in the menu bar, and “Window – Scale – 100%”. (The next time you start the simulator, it will have remembered these settings.)

Depending on the selected hardware (iPhone vs. iPhone 4), different textures will be used. Don’t worry if the HD version runs slowly on your Mac; on a real iPhone 4, it will run smoothly.

Preparations

First, you have to make sure that the tools “texture scaler” and “atlas generator” work. They can be found in the “sparrow/sparrow/util” directory of the download package. Have a look at the README files of those tools to find out how to prepare them.

Creating the graphics

When the tools work, we can start creating the graphics. Create the textures only for the high resolution (960×640). If you use a texture atlas, place your graphics in one directory per atlas. All other graphics are in a separate directory.

This leads to a directory structure like the following:

textures/
  atlas/
    tree.png
    house.png
    guy.png
  others/
    button.png
    background.png

As I said, those graphics are all targeting the high resolution. A tip: try to make the width and height of those textures even numbers. That way, the down-scaled versions we create below will have widths and heights that are whole numbers, and you avoid some aliasing issues later.

Now, do not add those graphics to the Xcode project! They are just the “raw material” for the graphics you use in your application. Save them in a directory outside of your project.

What we will do instead is the following: we will create two shell scripts that will use Sparrow’s tools to scale the graphics to the appropriate sizes and copy them to the project directory.

Script 1 – Normal Textures

First, we handle the textures that are loaded directly (they are not part of a texture atlas). Create the following script and save it into the “textures” directory from above. Let’s call it “scale_and_copy_textures.sh”:

#!/bin/bash

SCALE_TEXTURES=/sparrow_path/util/texture_scaler/scale_textures.rb
OUTPUT_PATH=/application_path/media/graphics

echo ""
echo "-> Renaming and copying high-res textures ..."
# no scale, add suffix
${SCALE_TEXTURES} -s 1 -a @2x others/*.png ${OUTPUT_PATH}/2x

echo ""
echo "-> Resizing and copying low-res textures ..."
# scale by 50%, sharpen
${SCALE_TEXTURES} -s 0.5 -r others/*.png ${OUTPUT_PATH}/1x

echo ""
echo "Done!"

Modify the two variables at the beginning so that they point to Sparrow’s texture scaler and to your game’s media directory. Before we can execute the script, we have to make it executable. Open the terminal and type:

cd path_to_textures/
chmod u+x scale_and_copy_textures.sh

Now you can execute it by calling

./scale_and_copy_textures.sh

If everything worked, this will create the following files in the output directory:

/graphics
  /1x
    button.png
    background.png
  /2x
    button@2x.png
    background@2x.png

The “2x”-folder contains the original graphics. The suffix “@2x” was added to the filenames. We’ll see later what that’s for. The folder “1x” contains the downsized and sharpened textures. (If you don’t want them to be sharpened, remove the “-r” flag in the script).

Script 2 – Atlas Textures

Thanks to Sparrow’s atlas generator, the process of creating the two atlases is just as simple. Create the script “create_and_copy_atlas.sh” in the same directory as the other script:

#!/bin/bash

GENERATE_ATLAS=/sparrow_path/util/atlas_generator/generate_atlas.rb
OUTPUT_PATH=/application_path/media/graphics

echo ""
echo "-> Creating High Resolution Atlas ..."
# no scale
${GENERATE_ATLAS} atlas/*.png -m 2048x2048 ${OUTPUT_PATH}/2x/atlas@2x.xml

echo ""
echo "-> Creating Standard Resolution Atlas ..."
# shrink by 50%, sharpen, and copy
${GENERATE_ATLAS} -r -s 0.5 atlas/*.png ${OUTPUT_PATH}/1x/atlas.xml

echo ""
echo "Done!"

The maximum size of the HD atlas is 2048×2048 pixels; that’s the maximum size of a single texture on iPhone 4. The smaller atlas has a maximum size of 1024×1024; that size is supported by all iPhone/iPod variants. Again, the smaller textures were scaled down to half of the size and sharpened.

Just like before, you have to make that file executable before you can start it:

cd path_to_textures/
chmod u+x create_and_copy_atlas.sh
./create_and_copy_atlas.sh

Now, the graphics directory should contain all of our textures:

/graphics
  /1x
    button.png
    background.png
    atlas.xml
    atlas.png
  /2x
    button@2x.png
    background@2x.png
    atlas@2x.xml
    atlas@2x.png

Preparations complete!

Phew! OK, that was quite a bit of work — but now, everything is prepared. From this moment on, when you add a new texture or change an existing one, all you have to do is to start up the corresponding scripts.

Using those Textures

Sparrow 0.9 makes it very easy to use those HD textures. You develop your game just like before, with a stage size of 480×320. All you have to do is to add the following line at the beginning of your application delegate:

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
  [SPStage setSupportHighResolutions:YES];
  // ...
}

Add all textures to your Xcode project (low and high resolution). Now, create SPImages and SPTextureAtlases just like before — no need to add the “@2x” suffix!

SPImage *background = [SPImage
    imageWithContentsOfFile:@"background.png"];
SPTextureAtlas *atlas = [SPTextureAtlas
    atlasWithContentsOfFile:@"atlas.xml"];

Behind the scenes, Sparrow will load the correct texture for you. The “width” and “height” properties of the loaded images and textures will always be the size of the low resolution (!) textures. That way, you can pretend that you are developing the game only in the low resolution. The HD-version will be a side-product you don’t have to think about while you are writing your game in Xcode.

Last words

This tutorial should have shown you nearly everything you need to know to create your next game in HD.

One thing I left out is Bitmap Fonts. Sparrow has no tool for that on its own. I recommend you use the bitmap font generator by AngelCode. To use bitmap fonts in HD, create the font files two times: once with the high resolution and the suffix “@2x”, and once with half the size (and no suffix). The demo project contains a bitmap font that shows you what the files should look like.

I think that should be it! If anything is unclear, just post your question below or in the forum — as always. Good luck!

UPDATE: What about the iPad?

You will have noticed that this post was only about the iPhone and iPod variants, not the iPad. Here’s the reason for this:

When you create an iPad-only application, there’s nothing special you have to think about. The SPView and SPStage objects will have a size of 1024×768, and you create textures for that size. That should be straight forward.

However, so-called “Universal Apps”, which contain iPad and iPhone/iPod versions within one application bundle are bit special. Currently, the “@2x”-textures are not loaded automatically on the iPad (and you’d need to modify the Sparrow source to do so).

Why is that so? Well, first of all, I expect that as soon as iOS 4 is released on the iPad, I bet that Apple will start up applications that were built for the retina display in full screen mode (well, at least in 960×640). That means that the application will run in high definition automatically.

Second, for a real iPad-app (universal or not), you normally don’t want to simply scale up everything, anyway. An iPad application should make use of the additional screen space, not just display everything twice the size. So I’m afraid you will have to use a different set of textures for the iPad, anyway (in scale, somewhere between the HD and LD textures), and move the controls and graphics to different positions. If that is not feasible: as I said above, I am confident that iOS 4 on the iPad will take care of the simple “double size” solution.

If I am mistaken about Apple’s plans — don’t worry, in that case, a Sparrow update will take care of that! :-)

del.icio.us Digg StumbleUpon Google Twitter Facebook
9 Comments

Sparrow Game Programming Tutorial

ManiacDev.com has just posted a great tutorial that might be interesting for those of you who are just starting to develop their first game with Sparrow, or who want to get an introduction on game development with Sparrow.

The extensive tutorial shows you how to create a simple action game from start to finish. You can see the final result in the video below!

Check it out here: Beginner iPhone Action Game Programming Tutorial

del.icio.us Digg StumbleUpon Google Twitter Facebook
0 Comments

No chicken: Sparrow 0.9 is out!

Hello everybody! I am happy to announce that Sparrow 0.9 has just cracked its eggshell and found its way to the download section.

Without further ado, I’ll describe the most important changes in the following sections. The detailed change list is, as always, part of the download package.

Beware: Interface Changes

There’s one thing we had to change for performance reasons. If you use the methods “colorOfVertex:” or “texCoordsOfVertex:”, the ID of the vertices has changed.

  • old order: 0 = top left, 1 = top right, 2 = bottom right, 3 = bottom left
  • new order: 0 = top left, 1 = top right, 2 = bottom left, 3 = bottom right

Sorry for that! But I guess that those methods are not used by the majority of Sparrow users, and it should be easy to change those calls. The alternative would have been for Sparrow to change the IDs internally, but I thought it was better to make the change now instead of carrying a workaround in all future versions of Sparrow.

Other things you should be aware of: Sparrow 0.8 requires the iOS SDK in version 4. The “Base SDK” of all projects was changed to “iOS 4.0″. Of course, you can still deploy to older system versions — that’s the “Deployment Target” setting of your project. That’s the approach that is recommended by Apple.

But now to the real enhancements!

Performance improvements

Isn’t that the coolest benefit of using a framework? You upgrade to a new version, and your application just runs smoother and faster. Better than a free lunch! :-)

The changes won’t be visible when you start the benchmark (part of the demo project), though. The biggest changes were made in parts that are not tested by the benchmark, namely:

  • Touch Events
  • Rendering of Bitmap fonts (SPTextField)

The first change is a direct result of the huge number of objects in the higher levels of “Twins”. Touching a cell in those levels led to a visible performance drop. Well, not any more!

The other thing is something I wanted to improve right from the beginning, but never found the time. Now, all glyphs of a text that uses a bitmap font are sent to OpenGL simultaneously, which makes rendering of those texts much faster (3x-4x!).

Support for high resolution screens

It’s now extremely easy to create your game with crisp, sharp textures for the iPhone4. That’s achieved with the same convention as in Apple’s core libraries: just add the suffix “@2x” to the filenames of your textures, and they will be loaded automatically instead of the low resolution textures — only on devices with an HD display, of course. This works with all kinds of images: plain textures, texture atlases, bitmap fonts.

All you have to do is enable the feature by calling “[SPStage setSupportHighResolutions:YES];” at the beginning of your game.

The demo project is now in full HD — just change the device type of the simulator to see it in action. Other than the line above, no changes to the code of the demo were necessary!

Texture atlas generator

When you work with HD textures, it’s a lot of work to create all textures in two resolutions … normally. But Sparrow has got its own texture generator now, which does all the work for you! Create your images in the high resolution, and then let the tool create two texture atlases for you: the high resolution atlas, and a scaled down version. It even supports automatic sharpening!

Here’s a small introduction — a detailed description and installation instructions can be found in the README file (sparrow/util/atlas_generator/README).

# Basic usage: creates "atlas.xml" and "atlas.png" from the
# provided images
./generate_atlas.rb input/*.png output/atlas.xml  

# The same with some options
./generate_atlas.rb --scale 0.5 --padding 2 --sharpen \
                    --maxsize 2048x2048 *.png atlas.xml

The next blog entry will show you in detail how to use this feature to create your next game in HD.

Miscellaneous

In brief, some other minor changes:

  • Another utility, the “texture resizer”, can be used to resize those textures that are not part of a texture atlas
  • Support for loading textures and sounds outside of the application bundle
  • SPMovieClip now dispatches “SP_EVENT_TYPE_MOVIE_COMPLETED”
  • SPJuggler’s “delayInvocation”-method now retains its arguments, which makes it easier to use
  • fixed several bugs (thanks to all of the reporters!)

Last words

I’m very happy with the latest version of Sparrow. As you can see, we added a lot of functionality without bloating the interface — most functionality just works behind the scenes. The code base was also cleaned up in several places.

We are also proud to announce that several games have appeared in the app store that are powered by Sparrow! I’m looking forward to presenting them in a separate blog entry.

Now, happy upgrading! If you encounter any problems after the upgrade, don’t hesitate to post them in the forum — we tried our best to test everything, but you never know!

del.icio.us Digg StumbleUpon Google Twitter Facebook
5 Comments