Monday, December 17, 2012

Using Torque and Thrusters to Move and Rotate a Player-Designed Spaceship

While working on a game in which the spaceships are designed by players and can be partially destroyed, I encountered an interesting problem: moving a ship around using thrusters is not an easy task. You could simply move and rotate the ship around like a car, but if you want ship design and structural damage to affect ships’ movement in a believable way, actually simulating thrusters could be a better approach. In this tutorial, I’ll show you how to do this.
Assuming a ship can have multiple thrusters in various configurations, and that the ship’s shape and physical properties can change (for example, parts of the ship could be destroyed), it is necessary to determine which thrusters to fire in order to move and rotate the ship. That’s the main challenge we need to tackle here.
The demo is written in Haxe, but the solution can easily be implemented in any language. A physics engine similar to Box2D or Nape is assumed, but any engine that provides the means to apply forces and impulses and query the physical properties of bodies will do.

Try the Demo

Click the SWF to give it focus, then use the arrow keys and the Q and W keys to activate different thrusters. You can switch to different spaceship designs using the 1-4 number keys, and you can click any block or thruster to remove it from the ship.

Representing the Ship

This diagram shows the classes that represent the ship, and how they relate to each other:
Gamedev Maths and Physics: Using Torque and Thrusters to Correctly Maneuver a Player-Designed Spaceship
BodySprite is a class that represents a physical body with a graphical representation. It allows display objects to be attached to shapes, and makes sure that they move and rotate correctly with the body.
The Ship class is a container of modules. It manages the structure of the ship and deals with attaching and detaching modules. It contains a single ModuleManager instance.
Attaching a module attaches its shape and display object to the underlying BodySprite, but removing a module requires a bit more work. First the module’s shape and display object are removed from the BodySprite, and then the structure of the ship is checked so that any modules not connected to the core (the module with the red circle) are detached. This is done using an algorithm similar to flood fill that takes into account the way each module can connect to other modules (for example, thrusters can only connect from one side, depending on their orientation).
Detaching modules is somewhat different: their shape and display object are still removed from the BodySprite, but are then attached to an instance of ShipDebris.
This way of representing the ship is not the simplest, but I found it to work very well. The alternative would be to represent each module as a separate body and “glue” them together with a weld joint. While this would make breaking the ship apart much easier, it would also cause the ship to feel rubbery and elastic if it had a large number of modules.
The ModuleManager is a container that keeps the modules of a ship in both a list (allowing easy iteration) and a hash map (allowing easy access via local coordinates).
The ShipModule class obviously represents a ship module. It’s an abstract class that defines some convenience methods and attributes that each module has. Each module subclass is responsible for constructing its own display object and shape, and for updating itself if needed. Modules are also updated when they’re attached to ShipDebris, but in that case the attachedToShip flag is set to false.
So a ship is really just a collection of functional modules: building blocks whose placement and type defines the behavior of the ship. Of course, having a pretty ship just floating around like a pile of bricks would make for a boring game, so we need to figure out how to make it move around in a way that is fun to play and yet convincingly realistic.

Simplifying the Problem

Rotating and moving a ship by selectively firing thrusters, varying their thrust either by adjusting throttle or by turning them on and off in quick succession, is a difficult problem. Fortunately, it is also an unnecessary one.
If you wanted to rotate a ship precisely around a point, for example, you could do that simply by telling your physics engine to rotate the whole body. In this case, however, I was looking for a simple solution that isn’t perfect, but is fun to play. To make the problem simpler, I’ll introduce a constraint:
Thrusters can only be on or off and they can’t vary their thrust.
Now that we’ve abandoned perfection and complexity, the problem is a lot simpler. We need to determine, for each thruster, whether it should be on or off, depending on its position on the ship and the player’s input. We could assign a different key for each thruster, but we’d end up with an interstellar QWOP, so we’ll use the arrow keys for turning and moving, and Q and W for strafing.

The Simple Case: Moving the Ship Forwards and Backwards

The first order of business is to move the ship forwards and backwards, as this is the simplest possible case. To move the ship, we’ll simply fire the thrusters facing in the direction opposite to the one we want to go. For example, if we wanted to go forward, we’d fire all the thrusters that face backwards.
Read more: Using Torque and Thrusters to Move and Rotate a Player-Designed Spaceship

Flash Haxe Gaming SDK, their tools, our tools

So Adobe released a few weeks ago its Gaming SDK for flash. The package includes Starling, Away3D and Feathers, three well know quality open source ActionScript3 libraries. You can easily find some externs for most of them on http://lib.haxe.org, which is great! However, during the development of my last game (which used Starling and Haxe) I found out that using haxelibs wasn't enough. A lot of good stuff is happening in the AS3 side, Starling is improving day after day on Github, users create really useful extensions for it. Time is precious and we don't want to write externs for everything or rewrite everything in haxe do we? Thanks to the great haxe/flash support, we can easily use all the good stuff in a matter of seconds, we can hack AS3 code and use the result from Haxe too. In this post I will try to teach beginners how to fish AS3 :)
  • how to compile a bunch of .as files into a .swf using the Flex SDK.
  • how to use those .swf files in haxe (with no extra work)
  • how to patch things when haxe is not happy with the .swf
We'll end up with the entire Adobe Gaming SDK, and more, for Haxe. But the journey is more important than the destination. NOTE: If you are not interested in the process and just want the SDK, I created a bunch of github repositories to host the results. See the test repository to learn how to play with it https://github.com/labe-me/haxe-gaming-sdk-test NOTE: I do not intend to write any extern for these libraries (I am too lazy for that), hence I won't submit them to haxelib. Feel free to use my work in any way you want to create nice haxelib packages. As far as I am concerned I really enjoy the haxelib git support :) Start. We are going to compile .as files, you'll need to install the Flex SDK. Let's learn how it works with Starling. (1) get the library sources:
[...] read more: Flash Haxe Gaming SDK, their tools, our tools

Thursday, December 13, 2012

Creating a Custom Virtual Keyboard

Although AIR for iOS offers access to the iOS virtual keyboard, you have limited control over the type of keyboard that appears. If you want additional keyboard configurations within your Flash project then you’ll need to build your own custom keyboard component. Although this will require some development effort it will allow you to tailor the user experience. For certain apps such as games, you may actually find a custom keyboard is the preferred option, as it will better fit your visual design.
Let’s see how to create one using Flash.
Flash iOS Apps CookbookThis tutorial is a previously unreleased recipe from Flash iOS Apps Cookbook and supplements the content found in Chapter 7, Working with Text and the Virtual Keyboard.
Flash iOS Apps Cookbook provides the recipes required to build native iOS apps using your existing knowledge of the Flash platform. Whether you want to create something new or simply convert an existing Flash project, the relevant steps and techniques are covered, helping you achieve your goal.

Getting Ready

An FLA has been provided as a starting point.
Download this recipe’s accompanying source bundle and open chapter7/recipe8/recipe.fla into Flash Professional.
The visuals for this application have already been created. Sitting on the stage is a virtual keyboard and a dynamic text field. The text field will be used to output what the user types.
The dynamic text field has been named field while the movie clip instance that represents the virtual keyboard has been named keyboard.

Entering a player's name with a custom virtual keyboard.
With the Selection tool (V) selected, double-click on the keyboard instance to examine its timeline. The keyboard contains 28 keys – 26 for the letters of the alphabet, an ok key for when the user is finished typing, and a del key to delete a character. You’ll find that each alphabetic key is represented by its own movie clip and that the instances are named a_key to z_key. This naming convention makes it easy to determine the letter that a key represents by simply examining the first character of its instance name. The remaining two keys have instance names of ok_key and del_key. Additionally there’s a movie clip named surface that sits beneath the keys and represents the keyboard’s body.
Double-click on any one of the keys to examine its timeline. Each is represented by two frames, where the second frame will be shown when the key is being pressed. The movie clip symbol for each key is linked to a class named Button, which was introduced in the Handling user interaction recipe from Chapter 4. Open Button.as and familiarize yourself with the code.

How to do it…

Perform the following steps.
From Flash, select File | New and create a new ActionScript 3.0 class. Name it VirtualKeyboard.
  • Add the following ActionScript to the class:
    [...]
    Read more: Creating a Custom Virtual Keyboard
  • Wednesday, December 12, 2012

    Enable Advanced Telemetry on Flex or old SWFs with SWF Scount Enabler

    Adobe Scout allows developers to profile SWFs like never before. The telemetry data sent by the release Flash Player to Adobe Scout is by default only set to send basic telemetry data. To be able to see data for the AS3 sampler, Stage3D rendering, and DisplayList rendering you have to enable the SWF (password is optional).
    This is done by using the newer asc2 compiler that comes in Flash Builder 4.7 or in the AIR sdk found in the Gaming SDK from Creative Cloud. Currently asc2 only works with ActionScript projects and implements a new flag called -advanced-telemetry or a check box in Flash Builder 4.7 ActionScript project properties.
    To enable SWFs that don’t use asc2, mainly Flex apps or legacy SWFs, you need to use a script to write a specific SWF tag into the SWF file. This doesn’t change the SWF abc code but just adds a SWF tag that Flash Player will use to start sending telemetry data. There is a python script written to help with writing this tag. But the python script requires python and I wanted something a bit easier to use so I created SWF Scout Enabler.

    To use the application all you need to do is drag your SWF into the application and it will create a new SWF (or override if you give it a “” suffix) that is enabled for advanced telemetry.
    The application will also save the last suffix and password used. It also has the ability to re-process the last processed file by clicking on the top right box image.
    Last but not least, the full source of the application can be found on github.
    Download the SWF Scout Enabler AIR application.
    I need to thank Joseph Labrecque for testing out the app.
    Note: This app has been tested on a bunch of SWFs but if it is not working let me know. There seems to be a bug with Adobe Scout on AS2 SWFs older than version 8. Adobe Scout will never do ActionScript sampling on AS2 SWFs but it will do basic telemetry.

    Read more: Enable Advanced Telemetry on Flex or old SWFs with SWF Scount Enabler

    Tuesday, December 11, 2012

    Animating With Asset Sheets: An Alternative to Blitting

    So you’ve got your awesome game in the works, it’s got all sorts of complex physics, epic enemy AI or what-have-you. But it feels lifeless. You want some OOMPH, you want some animation!
    So if you go and look up how to animate, the first answer you come across will most likely be a method using spritesheets and blitting. In fact, almost all tutorials on the web talk about nothing but blitting, as if there’s no other way to animate. But in my experience, there’s a better way to animate your orcs and goblins!
    This method could be called animating with asset-sheets – or more technically, tweening with asset-sheets – as opposed to using sprite-sheets. Before we get into exactly what this means, let’s consider an important question:

    What’s Wrong With Blitting?

    Below are some reasons as to why you would not want to use blitting in certain cases.

    1. It Takes a Lot of Space

    Whether we’re talking about RAM or disk space, sprite sheets can easily clog things up. Especially if you’re trying to make HD graphics. Huge sprite sheets may have to be split into multiple PNGs, taking up precious RAM and skyrocketing your game’s size if you’re not careful.

    2. It’s Not Dynamic

    What happens when you want to speed up an animation? You could skip some frames, but what about slowing down? The animation would look choppy and ugly. Even if you want to only support 60 fps, what if a computer can run the game faster? You could have jaw-droppingly smooth animations at higher frame rates with no extra work, and it would also look good if you chose to change the game’s frame rate at any time.
    And what if you wanted something to happen when the player’s arms reached some place? Or to have him pick up something? You’d need to manually mark his arm throughout the animation, which may be time-consuming as you can’t get any data about where any of his limbs are from a sprite sheet.

    3. It Doesn’t Allow You to Make Transitions

    What happens when the player is running and suddenly jumps? It cuts to the jump animation right away. This looks choppy, and this would happen every time the animation transitions to a new state. You’d have to make a transition for every pair of animations you have, which is not only insanely time consuming, but also has the adverse effect of increasing your RAM usage as discussed earlier.

    The Alternative

    Using asset-sheets not only allows the animations to be dynamic and scale up with any FPS, as well as transitioning smoothly between any two states, but also takes a tiny tiny amount of disk space and RAM compared to blitting!
    This isn’t even very new. Some popular games use it, like the recently popular Closure.  Its only limitation is that it can’t do frame-by-frame (FBF) animation, since it relies on tweening – so if you have complex explosions, you’ll have to use sprite sheets.
    But for a lot of cases, you’ll find you won’t need to, and it’s more than worth the effort to have a system like this for your game, as some games could rely completely on this, shaving off a ton of overhead. It’s also really cool because it’s similar to how you might animate a 3D game!
    So to summarize:
    Gamedev Animation With Asset-Sheets: An Alternative to Blitting

    Let’s Dive Right In

    This is a character and his asset sheet.
    Gamedev Animation With Asset-Sheets: An Alternative to Blitting
    As the name implies, an asset sheet is a PNG with all the limbs/assets of the character or object separated.
    And here is the animation data in JSON (of course, you can use whichever format you prefer to work with):
    //this snippet shows the first three frames of the "Body" animation
    "-name":"Body",
    "Frame": [
    {
     "-x":"0.65",
     "-y":"-64.45",
     "-rotation":"0.000"
    },
    {
     "-x":"2.45",
     "-y":"-64.45",
     "-rotation":"0.279"
    },
     "-x":"3.30",
     "-y":"-64.05",
     "-rotation":"0.707"
    }
    
    Now combining these two together in an awesome engine, you get:
    Gamedev Animation With Asset-Sheets: An Alternative to Blitting
    And unlike a blitted animation, this could speed down or up, or transition very smoothly. So this is what we'll be doing.

    Step 1: Exporting Your Asset Sheet

    The first step is to get your asset-sheet ready. You can do this in any number of ways. The point is to end up with a sheet containing the assets and a data file containing the positions of the assets in the sheet. This is the exact same method as for making a spritesheet, except in lieu of sprites you add separate assets.
    Export your player's limbs and pieces as individual PNGs, then use a program like Texture Packer to group them into a sheet. There are other programs, but I personally prefer Texture Packer because of how versatile and feature-rich it is.
    Tip: Whatever software you use to make your sheets , make sure there is at least 2px of padding between each asset and 1px extrusion. This will prevent some nasty problems in the future.

    Step 2: Exporting Your Animation Data

    [...]
    Read more: Animating With Asset Sheets: An Alternative to Blitting

    Tuesday, December 4, 2012

    Introducing Game Developer Tools

    I am really excited about what happened tonight. We just announced the introduction of the Adobe Game Developer Tools on Creative Cloud. You can read the official announcement here. As part of this, we are introducing three new products: Adobe Gaming SDK, FlasCC and Adobe Scout, which I have been working on for a year now. Here is a video about Adobe Scout and why it is going to change everything for your as a developer: I wrote a full article on how to get started with Scout. Make sure you check it out! If you have any questions, check the Scout forums! If you want to take a deep dive in Scout you can also check the video tutorials here. We also wanted to provide a great out of the box experience for developers to get started with the stack. Provide a nice package that allowa developers to get up and running quickly without having to hunt for the frameworks needed, the compilers and right documentation. That's why we are also introducing the Gaming SDK: The Gaming SDK contains the key frameworks you guys need to use to create fast performing 2D and 3D GPU games, but also much more, from the ATF tools to iOS ANEs. Starling, Feathers and Away3D are officially supported by Adobe and part of the Gaming SDK. It provides to you a one stop shop package to get started with the technology, we hope you guys will enjoy it! For those of you guys doing native development and interested in porting native games to the desktop, you can now use FlasCC (formerly named Alchemy), which is now release quality and supported.

    Read more: Introducing Game Developer Tools