Thanks to prodding and pleading by users I’ve decided to bite the bullet and add support for tile animations that newer builds of Tiled Map Editor allow through its Animation Tile Editor.

Tile Animation Editor

In a previous tutorial I demonstrated creating animations by using a combination of layers, tags, and specialized runtime behaviors. This approach is much better.

Like everything I else I try to do with Tiled2Unity, the animations from Tiled just work without any extra modifications. To achieve that, I’ve added a TileAnimator script that is automatically added to your prefab during the import process if animations are detected.

Tile Animator instances

Word of warning: Tiled layers are represented as meshes in Unity. In order to support animations the TileAnimator instances must modify these meshes in real-time. Under some conditions and platforms this may degrade performance. (I doubt it will be any worse then other attempts at animating tiles though.)

What You’ll Need

In order to get Tiled animations into your Unity projects through Tiled2Unity you will need the following:

  • Tiled2Unity version 0.9.5.3 or later (download here)
  • A daily build of Tiled Map Editor that support the Tiled Animation Editor. I used the Aug 1st, 2014 build. (download here)

As of this writing the collision and animation editors in Tiled are not in a stable build, hence the need to get a daily build.

Example Project

Being a big fan of the Zelda series I’ve taken a room out of the Desert Palace from The Legend of Zelda: A Link to the Past as an example. I like how the animated water and lamps bring a bit of life to the room – and no custom scripting or sprite objects are needed.

Tile Animations

You can download the example project here to see it for yourself. It includes both the final Unity project and the source Tiled files (map and textures).

Happy developing.

{ 10 comments }

Edge Colliders for One-Way Collision

(Note: You can play the results of this tutorial in the Unity Web Player here. You can also find the Unity package and source Tiled files by downloading here.)

Judging from the emails I’ve been getting, my little Tiled2Unity tool is proving to be useful for developers wanting to bring their Tiled Map Editor levels into their Unity projects.

The best received feature in Tiled2Unity is the ability to build up collision geometry from the tiles you lay down — but it only supported creating a PolygonCollider2D from rectangle and polygon objects. With the release of Tiled2Unity 0.9.3.0 (download latest Tiled2Unity here),  support has been extended to polylines which are represented as EdgeCollider2Ds in Unity.

EdgeCollider2D Example

The most obvious use of this feature is for the type of one-way collision that you find in so many old 2D platforming games. That’s cool but I’ve put together a different kind of example that takes the moving platforms from Mega Man 2 (yes, again with the Mega Man references) and shows how they could be implemented with help from Tiled2Unity.

Moving Platform in Mega Man 2

These platforms move along a charted path and seems like a great use for the EdgeCollider2D class in Unity — but having to draw out that path by hand would be a total pain. Instead, we’re going to add polylines to the tiles that make up that platform path and have the Tiled2Unity exporter create the EdgeCollider2D object for us. This way we could change the visuals of the path and the physical colliders would automatically update to match.

Adding Polylines To Tiles

We start off with the platform-map.tmx file in Tiled …

Mega Man2 Map in Tiled

Just like we’d add polygons and rectangles to tiles in Tiled we can add polylines using the Tile Collision Editor.

Tile Collision Editor - Adding Polylines

After adding all the polylines to all the “path” tiles we can launch Tiled2Unity and preview the results …

Edge Collider Preview in Tiled2Unity

That path gets built into one continuous EdgeCollider2D component with 44 vertices which is exactly what we wanted. The example comes with a Platform sprite which is programmed to traverse that path (see the custom PlatformCharacterController.cs script).

Tiled2Unity Map Exported to Unity With EdgeCollider2D

And we’re done. Feel free to download all the tutorial files or play the demo. Send questions to me via the comments or email. Happy developing.

{ 11 comments }

The Real Life Adventures of MegaDad

(Note: All the examples in this post are playable in the Unity Web Browser here.)

I recently introduced my Tiled2Unity Utility where I showed how to get started with Unity2Tiled and walked us through a couple of simple examples.

Now I want to show off some actual gameplay. In these examples we’ll see how a “real” game could interact with our exported Tiled maps. We’ll be introduced to concepts like setting Unity Tags and Layers automatically and reacting to colliders. I’ll show you how I achieve tile map animation and how you can hook into the Tiled2Unity import scripts to add custom behavior to your exported map layers and objects.

I keep these same goals in mind with these examples:

  • Exporting should be easy
  • Once exported, your prefabs should work without further tweaking – you just place them in the scene and you’re done

A Quick Word on Character Controllers (and Mega Dad)

Mega DadThe focus of these tutorials is Tiled map files in Unity through Tiled2Unity but I did invest some time in a 2D platform character controller using the CharacterController2D provided by prime[31] as a starting point.

Also, this work is strongly influenced by the Mega Man franchise of the NES golden-age. This will not surprise anyone that knows me. My daughters, being well-aware of my affinity for Mega Man, have taken to calling me Mega Dad at times so my hobbyist programming often includes the sprite I’ve made for the nickname.

Get the Tutorial Files

All the scripting, art, and Tile source files (TMX format) used for these examples is available for download here:

Download Mega Dad Adventures Example Files (.zip)

The zip contains two sections:

  1. The Unity package containing all the functionality and scripting found in this tutorial (MegaDadAdventures.unitypackage). Just import this into Unity — everything needed to run these examples is there.
  2. The Tiled Map Editor TMX source files. These were exported into the Unity package by Tiled2Unity.

Simple Example: No Collision or Gameplay

The simplest use of Tiled2Unity involves a decorative Tiled map in your Unity project. For this, I’m using Magma Man’s lair from Mega Man 9 represented here in Tiled map form …

Magma Man - No Collision

There’s nothing special about this and no preparation is needed before export. You can find it in the simple-no-collision scene in the example where it just sits there with a camera on it.

Simple Example with Collision

For the Tiled file MagmaManLair-WithCollision.tmx I’ve used the Tile Collision Editor to add collision to all the tiles that I’d expect our playable character to collide with.

Simple Map with Collision

Using the Tiled2Unity previewer I can see how the collisions would appear in Unity before I export.

Magma Man Collision Preview

I purposely chose a screen from one of the Mega Man games that had some interesting collision in it to show the kind of complexity that Tiled2Unity can handle. We can see the exported results in the simple-with-collision scene. This scene introduces our Mega Dad sprite as well. You can move him around with the arrow keys and jump with spacebar and see that he’s colliding with the PolygonCollider2D geometry as we’d expect from a Mega Man type game.

Playing the Magma Man Lair scene

Note that all exported layers and objects are, by default, assigned the Default physics layer but we could change that if we wanted to (and will later with more complicated scenes). Since our Mega Dad sprite is set up to collide with Default physics we don’t need to make any changes yet.

Collision with Slopes

The collision geometry from the last example is actually one PolygonCollider2D object but it looks a bit boxy and doesn’t demonstrate the flexibility we have with the shapes of colliders we can use with Tiled2Unity.

There are no examples of sloped collision in the Mega Man NES games so for this example I’m going to borrow art from Capcom’s NES port of Strider — which had plenty of sloped terrain in it.

Here you can see the RedDragon-WithSlopes.tmx file open in Tiled with one of the tiles having a single triangle-polygon on it for collision …

Sloped Collision

And again, the Tiled2Unity previewer …

Slopes Preview

This map was exported and added to the slopes scene in the downloadable example. Here you can see Mega Dad standing on the sloped terrain.

Sloped Collision in Play

Games with such terrain in them usually build their sprites with this in mind so they look better on a slope, but I think you get the idea.

Still, we can make this better through using Tiled2Unity’s ability to set the Sorting Layer on an exported Tiled layer.

Sorting Layer and Order in Layer Properties

As you can see, Mega Dad looks a bit awkward when not on even ground …

Mega Dude Hanging

Games generally handle this by changing their sprite artwork or by changing their environment  to give it more depth or by using the foreground to hide the sprite’s feet.

Slope Examples

Taking a cue from Super Metroid, I’m going to put some railing in the foreground over our slopes.

Slope, with rails

Adding this to our map in Tiled is easy enough but now we’re doing something new with our scene in Unity: We need to render our sprite between two Tiled layers.

By default, Tiled layers are exported with the Default sort layer. Now we’ll want to purposely assign sorting layers. This Unity project has the following sorting layers in order:

  1. Background
  2. Default
  3. Foreground

(Our Mega Dad sprite renders to the Default sort layer in this example)

Each layer or object in Tiled supports custom properties and in order to change our Sorting Layer we add a custom property named unity:sortingLayerName to our layers.

Putting our Background Tiled layer in the Background sorting layer …

Background Sorting Layer

And putting our GuardRails Tiled layer in the Foreground sorting layer …

Foreground Sorting Layer

… we construct a prefab on export that hides our Mega Dad’s feet behind the foreground while he’s standing on a slope.

Hiding odd looking collision

Here’s the list of the properties we can set in Tiled that the Tiled2Unity exporter looks for when constructing a prefab:

  • unity:tag
  • unity:sortingLayerName
  • unity:sortingOrder
  • unity:layer (Layer is such an overloaded term. In Unity it means the “physics” layer.)

We often don’t want to set unity:sortingOrder as it is implicitly set for you by the order of Tiled layers in your TMX file. We’ll use unity:tag and unity:layer in interesting ways soon.

Note that should you try to use a Sorting Layer Name that does not exist in your Unity project that the importer scripts in Unity will let you know about it through an error in the Unity console:

Sorting Layer "Foreground" does not exist. Check your Project Settings -> Tags and Layers

Adding Gameplay with Tags

This next example is probably my favorite as the water scene in the Unity project is a good example of bringing Tiled maps to life in your Unity project.

Getting back into the Mega Man look and feel, the DiveMan-water.tmx Tiled map file borrows from the Dive Man stage of Mega Man 4. You’ll notice the Tiled layers are animating.

Animating Tile Layers

This is achieved in Unity scripting by simply selecting game objects based on their tags (AnimLayer1 and AnimLayer2) and toggling between them at a given framerate.

// A cheap an easy class that animates our Tiled layers
class LayerAnimator : MonoBehaviour
{
    public float TimePerLayer = 0.5f;

    private void Start()
    {
        StartCoroutine(AnimateRoutine());
    }

    private IEnumerator AnimateRoutine()
    {
        bool isLayer1Active = true;
        var layer1Objs = GameObject.FindGameObjectsWithTag("AnimLayer1");
        var layer2Objs = GameObject.FindGameObjectsWithTag("AnimLayer2");

        while (true)
        {
            foreach (var obj1 in layer1Objs)
            {
                obj1.SetActive(isLayer1Active);
            }
            foreach (var obj2 in layer2Objs)
            {
                obj2.SetActive(!isLayer1Active);
            }

            isLayer1Active = !isLayer1Active;
            yield return new WaitForSeconds(TimePerLayer);
        }
    }
}

All this script requires is that we have objects in our scene with the appropriate tags. This is where unity:tag comes in.

In Tiled, all we need to do is select the Tiled layers we want to toggle between and give them the AnimLayer1 or AnimLayer2 tag. For instance …

Setting Unity Tag

Once exported, our LayerAnimator component in the scene finds the GameObjects on our prefab and animates them.

Adding Gameplay with (Physics) Layers

Also in this example we have gravity changing for Mega Dad when he is inside water. Like the Mega Man games, this will slow his fall and allow him to jump much higher while in water.

This is achieved by having one of the Tiled layers (WaterVolume) being exported with the Water physics layer (again, I apologize for the overuse of the word ‘layer’ — it means different things in Unity and Tiled). We use a unity:layer custom property within Tiled …

Layer Property

Now all the tiles in this Tiled Layer with collision on them will be be gathered into a PolygonCollider2D with the Water physics layer.

Our Character Controller for Mega Dad is set up with a trigger that detects when it is in a water collider and changes Mega Dad’s response to gravity. We also tell Mega Dad to start breathing out air bubbles while within this collider in addition to spawning a “splash” sprite when he enters or exits the collider. It’s a nice example of interacting with maps exported with Tiled2Unity.

Water Trigger

Tiled Object Layers Can Have Colliders Too

Keeping with the water scene example, there are no tiles with collision off the upper left and right side of that map and we’d like to keep Mega Dad from falling out of the world with invisible collision. That’s where we can use the Object Layer features of Tiled which are, like Tile Layers, exported into the prefab hierarchy as GameObjects.

In this case, Tiled2Unity does not attempt to combine geometry into one collider. Since we are placing Rectangles, Ellipses, Polygons, and Polylines in Tiled separately they are themselves exported as separate GameObjects.

  • A Tiled rectangle object is exported as a BoxCollider2D
  • An Tiled ellipse object is exported as a CircleCollider2D (but only if it is a circle with equal width and height, Unity does not support ellipses)
  • A Tiled polygon object is exported as a PolygonCollider2D
  • A Tiled polyline object is exported as an EdgeCollider2D

To keep Mega Dad inside the level, I’ve added two rectangle objects to an Object Layer in the TMX file:

Adding Tiled Objects

Like other collisions we can see what they look like in the Tiled2Unity previewer …

Object Previewer

Once exported that gives us collision along the sides of our scene so that Mega Dad doesn’t fall out.

BoxCollider2D Blocking Player

Ladders With Custom Importing

One of the hard-learned lessons from my Mega Man vs Cut Man experiment is what a horrible pain in the ass ladders are to implement. The in-game mechanics of ladders are left, sheepishly, as an exercise of the reader but at least getting ladder geometry into a game can be made easier with Tiled2Unity.

First, in Tiled, we make a separate Tiled Layer for all ladders in the scene and paint some ladders with tiles.

Making Ladders in Tiled for export to Unity

Note that the ladders Tiled Layer is given the Ladders value for the unity:layer property. This will add all ladder collision into a special physics layer for us to manipulate later through custom scripting later but for now we can paint ladders with tiles as we wish in our Tiled map file.

What We Need from Ladders

Because of the way our Mega Dad character interacts with ladders we need to know, for each ladder instance, the following information:

  • The center-line (or spine) of each ladder
  • The top of each ladder
  • The bottom of each ladder

However, from Tiled2Unity, we get one PolygonCollider2D that represents all ladders in the Tiled Layer.

Ladder Have vs Need

We could lay down polylines in Tiled that get exported into EdgeCollider2D instances but if we move, add, or remove ladder tiles from our map then we have to manipulate our polylines as well. Instead, we can take advantage of the custom importing feature of Tiled2Unity and write a script that will add the EdgeCollider2D instances for us.

Use ICustomTiledImporter for Custom Importing from Tiled2Unity

Tiled2Unity provides an interface that allows you to add custom behavior to the prefabs it creates from exported Tiled map files. You only need to write a script class that inherits from ICustomTiledImporter with the CustomTiledImporter attribute. Tiled2Unity will use reflection to find such custom importers and instantiate them as part of the import process. (If order of execution is important use the Order property of the CustomTiledImporter attribute.)

// Example custom importer:
[Tiled2Unity.CustomTiledImporter]
class MyCustomImporter : Tiled2Unity.ICustomTiledImporter
{
    public void HandleCustomProperties(GameObject gameObject,
        IDictionary<string, string> keyValuePairs)
    {
        Debug.Log("Handle custom properties from Tiled map");
    }

    public void CustomizePrefab(GameObject prefab)
    {
        Debug.Log("Customize prefab");
    }
}

For this example we’re going to use the CustomizePrefab method to crack open the PolygonCollider2D instances belonging to ladders and add the EdgeCollider2Ds we desire.

// From CustomTiledImporterForLadders.cs
public void CustomizePrefab(GameObject prefab)
{
    // Find all the polygon colliders in the pefab
    var polygon2Ds = prefab.GetComponentsInChildren<PolygonCollider2D>();
    if (polygon2Ds == null)
        return;

    // Find all *ladder* polygon colliders
    int ladderMask = LayerMask.NameToLayer("Ladders");
    var ladderPolygons = from polygon in polygon2Ds
                         where polygon.gameObject.layer == ladderMask
                         select polygon;

    // For each ladder path in a ladder polygon collider
    // add a top, spine, and bottom edge collider
    foreach (var poly in ladderPolygons)
    {
        GameObject ladderTops = new GameObject("LadderTop-EdgeColliders");
        GameObject ladderSpines = new GameObject("LadderSpine-EdgeColliders");
        GameObject ladderBottoms = new GameObject("LadderBottom-EdgeColliders");
        ladderTops.layer = LayerMask.NameToLayer("LadderTops");
        ladderSpines.layer = LayerMask.NameToLayer("LadderSpines");
        ladderBottoms.layer = LayerMask.NameToLayer("LadderBottoms");

        // Create edge colliders for the ladder tops
        // We assume that every polygon path represents a ladder
        for (int p = 0; p < poly.pathCount; ++p)
        {
            Vector2[] points = poly.GetPath(p);

            float xmin = points.Min(pt => pt.x);
            float xmax = points.Max(pt => pt.x);
            float ymax = points.Max(pt => pt.y);
            float ymin = points.Min(pt => pt.y);
            float xcen = xmin + (xmax - xmin) * 0.5f;

            // Add our edge collider points for the ladder top
            EdgeCollider2D topEdgeCollider2d =
                ladderTops.AddComponent<EdgeCollider2D>();
            topEdgeCollider2d.points = new Vector2[]
            {
                new Vector2(xmin, ymax),
                new Vector2(xmax, ymax),
            };

            // Add our edge collider points for the ladder spine
            EdgeCollider2D spineEdgeCollider2d =
                ladderSpines.AddComponent<EdgeCollider2D>();
            spineEdgeCollider2d.points = new Vector2[]
            {
                new Vector2(xcen, ymin),
                new Vector2(xcen, ymax),
            };

            // Add our edge collider points for the ladder bottom
            EdgeCollider2D bottomEdgeCollider2d =
                ladderBottoms.AddComponent<EdgeCollider2D>();
            bottomEdgeCollider2d.points = new Vector2[]
            {
                new Vector2(xmin, ymin),
                new Vector2(xmax, ymin),
            };
        }

        // Parent the ladder components to our ladder object
        ladderTops.transform.parent = poly.gameObject.transform;
        ladderSpines.transform.parent = poly.gameObject.transform;
        ladderBottoms.transform.parent = poly.gameObject.transform;
    }
}

At first glance this may seem like a lot of work, but, once written, this script will now import all ladders for us in all our maps. We can place ladders with ease in Tiled and let the custom importer do all the heavy lifting.

You can see the results of this in the ladders scene included in the tutorial Unity package.

uni-cutman-ladders

Adding Spawners With Custom Import Scripting

With using the Tiled Map Editor as our 2D level editor we often need ways of marking up our worlds with some game-specific behaviors, with spawners for our game sprites being an obvious requirement.

Tiled allows us to place Tile Objects into an Object Layer. Moreover, our Tiles can have custom properties on them. Tiled2Unity allows us, through custom scripting, do get at these custom properties and manipulate the GameObjects they are attached to for game-specific behavior.

For this example we’re going to revisit a scene from the popular Mega Man 2 with the Appearing Block sprites from Heat Man’s stage.

Appearing Blocks in Mega Man 2

Placing these Appearing Blocks in Tiled is easily achieved by using Tile Objects in an Object Layer. Here I’ve distributed a number of such Tile Objects amongst three Object Layers in the HeatManBlocks.tmx file.

tiled-blocks

The important part here is with the Tile representing our Appearing Block that we’ve added a custom property spawn with the value AppearingBlock. We only need to do this once and then we can place as many of those Tile Objects we wish. We’ll write some code soon that consumes those custom property values and, within Unity, will attach GameObjects to our map prefab.

Exporting this map into Unity we can see the blocks we’ve placed represented as GameObjects in the prefab …

Tile Objects as GameObjects

… but right now they’re just empty, albeit with the right positional data imported from our Tiled map file.

In order to allow for game-specific importing of map data Tiled2Unity can hook into any custom properties we assign to our map, layer, or object data within our Tiled TMX files. This is achieved through the HandleCustomProperties function on the ICustomTiledImporter interface that we can inherit from in our Editor scripts. It passes in the dictionary of custom property name and value pairs as well as the GameObject that you’ve assigned such custom properties to.

Here’s an example of a custom importer script that looks for a custom AddComp property that we have set in Tiled and, during import, will add those components …

Custom Property in Tiled

[Tiled2Unity.CustomTiledImporter]
class CustomImporterAddComponent : Tiled2Unity.ICustomTiledImporter
{
    public void HandleCustomProperties(UnityEngine.GameObject gameObject,
        IDictionary<string, string> props)
    {
        // Simply add a component to our GameObject
        if (props.ContainsKey("AddComp"))
        {
            gameObject.AddComponent(props["AddComp"]);
        }
    }

    public void CustomizePrefab(GameObject prefab)
    {
        // Do nothing
    }
}

Going back to our example with blocks, what we want to do is look for a spawn custom property with a value of AppearingBlock, instantiate the appropriate sprite, and then attach it to our game object.

[Tiled2Unity.CustomTiledImporter]
class CustomTiledImporterForBlocks : Tiled2Unity.ICustomTiledImporter
{

    public void HandleCustomProperties(UnityEngine.GameObject gameObject,
        IDictionary<string, string> props)
    {
        // Does this game object have a spawn property?
        if (!props.ContainsKey("spawn"))
            return;

        // Are we spawning an Appearing Block?
        if (props["spawn"] != "AppearingBlock")
            return;

        // Load the prefab assest and Instantiate it
        string prefabPath = "Assets/Prefabs/AppearingBlock.prefab";
        UnityEngine.Object spawn = 
            AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));
        if (spawn != null)
        {
            GameObject spawnInstance = 
                (GameObject)GameObject.Instantiate(spawn);
            spawnInstance.name = spawn.name;

            // Use the position of the game object we're attached to
            spawnInstance.transform.parent = gameObject.transform;
            spawnInstance.transform.localPosition = Vector3.zero;
        }
    }

    public void CustomizePrefab(UnityEngine.GameObject prefab)
    {
        // Do nothing
    }
}

Now when we reimport the map we see that our spawned block sprites were added to the prefab hierarchy …

Spawned Object in Prefab

With these spawned sprite objects now in the prefab they can be manipulated by other runtime scripts to add the gameplay we’re looking for – platforming blocks that appear and disappear with a given timed pattern (see the custom-import scene to play the example).

heatman-blocks

Complicated Gameplay with Little Work

These examples may seem a bit involved but I feel it’s a good example of how one could mix unity-specific and custom properties in Tiled with some scripting in your Unity project to achieve behavior that is specialized to the game you are creating. (It actually took me a lot longer to document the examples in this blog post than it did to build this Unity project.)

Any questions? Found a bug? As always feel free to drop me a line in the comments or email me. Happy developing.

{ 11 comments }

A quick update on some Tileset settings that are now supported in Tiled2Unity. (With thanks to readers alerting me to such shortcomings.)

Note: You can download the newest version of Tiled2Unity here.

Alpha Color Key Support

Previously, the shader used by Tiled2Unity on the Unity side was dependent on the alpha channel of textures alone. Old-school games have a history of using a color-key for transparency though so I’ve followed the lead from Tiled Map Editor to support this in Tiled2Unity.

Tranparent color Tiled supported in Tiled2Unity

Note that in Tiled2Unity you can use both the transparent color and the alpha channel in the same Tileset/texture. You don’t have to go with just one transparency scheme.

Tilesets Made From Collection of Images

Tiled gives you the ability to create a Tileset from a collection of images. I always work with Tilesets where one image contains many tiles and didn’t even know this feature existed.

Tiled Tileset from Collection of Images

This is now supported but a word of warning: This will increase the number of textures and meshes in your Unity scene. I think it’s worth supporting for prototyping or the odd Tileset but as a rule you’re better served by grouping tiles into larger textures.

{ 0 comments }

Update: Most Tiled2Unity users will want to use the newer vertex scaling feature to scale their Tiled maps.

Tiled2Unity Scaling

A couple of weeks ago I released my free Tiled2Unity Utility, allowing developers to export their old-school and tile-based environments (built with Tiled Map Editor) into Unity with (one hopes) relative ease.

You can download the Win32 installer or zip file for Tiled2Unity from the Download Page.

Some of you requested a feature to control the scale of the prefab objects exported by Tiled2Unity, especially give that sprites in Unity2D projects default to a completely weirdo coordinate system where 1 pixel is equivalent to 0.01 units in Unity.

A short note on this: Unity uses Box2D behind the scenes for the physics engine. Box2D is great but it isn’t well suited for pixel-perfect retro game development in my opinion. Our retro games want to work with pixel units where our characters are some 24 or 48 units high and moves some 100 or 200 pixels a second. Box2D wants to work with real-world units where a given character is 1 or 2 meters high and is moved my Newton forces. I feel getting NES-era 2D platforming out of a modern day physics engine is not worth the headache but your mileage may vary.

But I digress. The point being, an important goal for Tiled2Unity is that your generated prefab, once exported from Tiled, is ready to go into your scene without further edits.

So for people that wish to use Tiled2Unity on projects with sub-pixel coordinate systems here’s how you can easily set up your Tiled maps to scale appropriately. Note: This will require you install the newer version of Tiled2Unity (0.9.1.0).

So You Want to Use Physics2D

Let’s say we’ve got the first lady of video games, Samus Aran, in your Unity project and you’ve imported the sprite with the default Pixels To Units setting of 100.

Samus in Unity

With this, we have a sprite image that is 26x43 pixels but has dimensions of 0.26x0.43 units in your Unity project. Using the minimalist-collision.txm Tiled map from the Tiled2Unity example as-is we’d end up with an exported background that is 100 times too large for our sprite to inhabit. Here she is between two blades of pixel grass …

Samus between 2 blades of grass

Setting the Scale in the Tiled File

We could just scale down the prefab we created by hand in the Inspector within Unity but I don’t want to do that every time we export the Tiled map. Instead, we’ll set a property within the map once …

Map property, unity:scale

unity:scale 0.01

Now when we export the Tiled map, our Tiled2Unity Utility looks for that unity:scale property on the map data (Tiled2Unity will complain if you try to scale layers or objects, btw) and the automatically created prefab will have the appropriate scale value assigned to it.

Once re-exported, here’s the final scene with Samus resting on collision geometry with sprite and background using coordinate system values of the same magnitude.

Samus and Environment at Scale

BTW, there are other properties you set in your Tiled map file that control the way your prefab is constructed.

  • unity:sortingLayerName
  • unity:sortingOrder
  • unity:layer
  • unity:tag

I’ll cover these soon in another post. In the meantime I’m happy to take suggestions for improvement.

{ 20 comments }

Tiled2Unity

(Note: ‘Minimalist’ example artwork is attributed to Blarget2 via OpenGameArt.org)

If you’ve been working on a 2D tile-based game in the last couple of years then there’s a decent chance you’re familiar with Thorbjørn Lindeijer’s excellent Tiled Map Editor. It’s what I used when creating the maps for Mega Man in Unity and I’ve now retooled and de-hacked my Tiled-to-Unity exporter (called Tiled2Unity Utility because naming things is hard) for general consumption by my fellow game developers  – free of charge under the MIT License. I sincerely hope others find it useful.

You can download the Tiled2Unity Utility from the Download Page.

Features:

  • Builds a Unity prefab out of your TMX map file
  • Supports all TMX layer formats (XML, CSV, Base64, gzip/zlib compressed)
  • Multiple layers and tilesets supported
  • Exports Object Layer as polygons, polylines, rectangles, circles
  • Tile Layer collisions supported (with slopes, odd-shaped polygons)
  • Polygon colliders can be concave, have holes, and be composed of separate polygons
  • Can assign Tag, Sorting Layer, Order in Layer, and (Physics) Layer of exported GameObjects through properties in Tiled
  • Support for customized creation of Unity Prefabs
  • Easy to use: In most cases, you simply export a TMX file into your Unity project and place the automatically generated prefab in your scene – no further edits needed

Limitations:

  • Orthographic map support only (Isometric and hexagonal map support in version 0.9.10.0)
  • Ellipse objects are ignored unless they are circular (there is no ellipse collider in Unity)
  • Object rotation is currently not supported (Object rotation added in version 0.9.9.0)
  • Tiled2Unity only runs on Windows out of the box (Prefabs exported into Unity will work on all devices though) (Note: See comments section here for support on other platforms)

Note that I made a purposeful decision not to support isometric maps*. It adds far too much complexity for something that I think is a bit of a hack. I feel orthographic maps should be used at all times and the illusion of top-down or side-scroller or isometric should come from the art, not some weirdo coordinate system. (Your mileage may vary but it’s not like the Nintendo Entertainment System had an isometric mode.)

*(Edit to add: Okay, I relent. Isometric and hexagonal map support has been added as of version 0.9.10.0.)

Tiled2Unity Uses Newer Features of the Tiled Map Editor

In order to assign collision data to tiles you will need to use the new Tile Collision Editor in Tiled.

Tile Collision Editor Menu Item

This Tiled feature is currently in beta* so you’ll need to get a version of the program from the daily builds here: http://files.mapeditor.org/daily/

For my development and testing I’ve used the May 23rd, 2014 build. (Builds older than April 24th, 2014 will crash if you have collision data in external tilesets.)

*(Edit to add: Not in beta anymore. Just download latest version of Tiled)

Getting Started with Tiled2Unity

Before you begin exporting Tiled data into Unity, your project needs to be aware of how it will import the *.unity2tiled.xml files that Tiled2Unity spits out. The scripts for this are part of the Tiled2Unity.unitypackage file found in the install directory.

There are two ways to import this package into your Unity project:

  1. From the Tiled2Unity install folder: Double click on the Tiled2Unity.unitypackage file
  2. From within Tiled2Unity: Just select the “Import Unity Package to Project” menu item

Import Tiled2Unity Unitypackage

In both cases, Unity will take you through the steps of installing the package into your Unity project. There’s a number of scripts and folders here. You’ll need them all.

Import all items

Now we’re ready to export some Tiled maps into Unity.

Using Tiled2Unity Examples

Your Tiled2Unity install contains a couple of TMX file examples. We’re going to open the minimalist.tmx file in Unity …

Minimalist map

We don’t need to run Tiled in order to export a TMX file into Unity, but I’ve set up a command in Tiled that will run Tiled2Unity for me.  This allows me to make my map edits in Tiled and then quickly export to Unity by pressing F5.

Setting Tiled2Unity command in Tiled

"c:\Program Files (x86)\Tiled2Unity\Tiled2Unity.exe" %mapfile c:\MyUnity\Test

The command is made up of 3 parts:

  1. The path to your Tiled2Unity install
  2. The %mapfile macro (this will be the same for all users)
  3. The path to your Unity project (you can leave this blank and use the Tiled2Unity GUI instead)

Hitting F5, now Tiled2Unity pops up with our map already loaded and ready to export to our Unity project …

Running Tiled2Unity from Tiled

Now, pressing the Big Ass Export Button will export an XML file (in this case, minimalist.tiled2unity.xml) to our Unity project where our importer scripts will create the meshes, textures, and materials needed and roll them all up into a prefab named after our TMX file.

Minimalist map in Unity

Now we can place the prefab into our scene hierarchy. (If our map was to be purely decorative then we’d be done.)

Minimalist prefab placed in scene

Adding Collision Geometry

Chances are most maps we make in Tiled for use in video games will require some collision geometry on them for sprites to interact with. Other solutions I’ve found on the internet or the Unity Asset Store require you to hand-place collision objects by hand in Tiled which I think is a total PITA. I’m going to show you how we can easily add complicated collision geometry (with holes, slopes, concave shapes, etc.) to our tile layers that are exported to Unity as PolygonCollider2Ds.

With Tiled still open on our minimalist map, bring up the Tiled Collision Editor an add a Rectangle or Polygon object that fully encloses the solid dark grey tile of our mini-tile tileset …

Add collision to tile

Let’s leave the other tiles alone for now and see how we’re doing. Press F5 again to bring up our Tiled2Unity exporter and press the Preview Exported Map button to see how the geometry would appear in Unity …

First collision preview

Here we can see how the geometry of just one tile will be combined into a polygon collider as the tile is repeated throughout the map. Note that, in the resulting collision mesh, there is actually four shapes here — two of which are rather awkward. Except for not matching the visuals, that’s actually okay, the PolygonCollider2D in Unity would handle this fine.

Let’s go back to Tiled and add polygons to our sloped tiles …

Adding sloped collision

(I recommend that Snap to Grid and/or Snap to Fine Grid is enabled when placing polygons in Tiled)

Previewing again we can see how sloped geometry will be added to the collision mesh …

Second preview

Again, this geometry could be exported into our Unity project and the PolygonCollider2D created from it would just work.

Going over all our darker tiles and adding polygons/rectangles I get a final preview that I’m pretty happy with …

Final preview

The best part of this is as we edit the map the collisions assigned to each tile move along with them. You add the geometry to your tiles once, create all the map data you like, and let the exporter take care of the rest.

Here’s the final exported prefab with our PolygonCollider2D in Unity …

Map with collision in Unity

And there you go, a 2D tile-based map, authored in Tiled, with collision, in your Unity scene.

Find any bugs? Is something not working as expected? Got a feature request that makes sense and won’t kill my social life? Feel free to email me.

By the way, the magic behind this polygon construction is courtesy of Angus Johnson’s exceptional (and open source) Clipper library. In my opinion, layer collisions is the most essential feature of Tiled2Unity and Johnson’s Clipper library worked for me the first time I tried to use it. C’est Magnifique! *kisses fingertips*

{ 96 comments }

Mega Man in Unity

by Seanba on March 16, 2014

Mega Man in Unity

After shipping Epic Mickey 2 (and before the heartbreaking closure of Junction Point Studios) I had a couple of months of comp time to unwind and sharpen the saw a bit.

I decided to spend my some time during that break getting to know the Unity game engine.

To be honest, I had to fight some strong biases in starting that exercise. I’m not sure how widely known the following sentiment is, but for programmers in big-budget, high-end AAA game development the idea of using an engine like Unity is considered weak sauce. Better to spend your time in C++ learning more about concurrency and data object model programming.

But I’ve been longing for some technology to help me prototype gaming ideas quickly and it sounded like Unity was the best contender.

I also decided that this would be the first time in my double life as a hobbyist game programmer that I was actually going to finish something. To that point I chose a beloved game from my childhood and decided to remake, in part, the original Mega Man from the NES golden days. I figured my love for the franchise would help get me past the eventual malaise that smothers every hobby project of mine once real life kicks in.

I’ve just recently finished the exercise and you can play the game in your browser here …

Mega Man in Unity

Only Cutman’s Stage

Like most old-time gamers I’ve spoken to, my experience with Mega Man started with Cutman’s stage — so that is the focus for this game. Other limitations on this Unity-powered game include …

  • Mega Man has no additional powers from any Robot Masters. The Mega Buster is his only weapon.
  • Enemies do not drop powerups, free lives, or any other items.
  • There is no scoring.

Obviously this is not a complete Mega Man game but fans of the original title will hopefully appreciate the 10 minutes or so of oldschool gameplay.

And fellow hobbyists might appreciate that this was accomplished with the free version of Unity.

Some Assembly Was Required

Still, with Unity being a 3D engine there were two important technologies I spent time on in order to display 2D assets:

  1. Sprites: I used the freely-available SpriteManager utility for sprite animation. In addition, I wrote a utility that took animations from GraphicsGale and generated code and data for each sprite.
  2. Tile-based Maps: I wrote a utility that transformed map data from Tiled Map Editor (a great little program for 2D enthusiasts, btw) into a Wavefront OBJ file that could be imported into Unity.

Ironically, I finished this project just as Unity 4.3 was being released so there’s a good bit of work here (especially with the sprites) I was planning to use for other titles that is now obsolete. That’s okay though as I’d much rather see sprites being first class citizens within Unity anyhow.

Was it Time Well Spent?

I started this project in December of 2012 and within a couple of weeks I pretty much had everything in place, with Mega Man running and jumping around Cutman’s level and a couple of the enemy sprites doing their thing. I was (and still am) pleased with how easy it is to work with Unity, even when you are trying to do something that game engine wasn’t really built for, like 2D sprite-based gaming.

After that short time I could have (and maybe should have) moved on to something original as the exercise of “learning” Unity was accomplished — but what I can say, I love that little Blue Bomber dude. I had fun with this.

How long did this take? It’s hard to say as I don’t do project management on my hobbies (what a depressing concept!). Yes, I started this nearly a year-and-a-half ago, but man, I also had to layoff some 30 of my closest programmer friends, shut down a studio, and find another job in that time as well. I only worked on this in spurts. Now, I’m just happy with the end result and I’m eager to focus on something else with my spare time. I hope some Mega Man fans give it a try and enjoy a small piece of nostalgia too.

And as far as Unity goes: I use it for all my hobby game programming projects now. I’d like to see the 2D components mature some more (Unity 4.3 is a great start to that) but overall I can’t think of any other (free) game engine that comes close to this one.

NOTE: I feel I should apologize for the occasional jittery scrolling and screen tearing in the playable Unity game. This appears to be an issue with the Web Player that other developers struggle with and as far as I’ve researched there’s no easy solution. If I’m wrong, email me the details. I’ll gladly fix it.

 

I’m embarrassed I didn’t realize it would be a problem until after the game was complete as I should have tested on the Web Player throughout development. That’s a total rookie mistake there.

{ 5 comments }

Note: The guys at 1 More Castle came up with a great idea: a day of blogging completely devoted to the review of games, new or old, retail or indie, that we may consider great. It’s an exercise of positive reflection on the titles that make us the gamers we are.

They’ve deemed April 8th to be international Review A Great Game Day. Dozens of such articles are available on their webpage now … and more are coming. I highly recommend a visit.

Below is my entry focused on a game that I hold dear. (Naturally, I waited until the last minute to write it.)

Double Dragon II: The Revenge: The Review

Title: Double Dragon II: The Revenge
Developer: Technos Japan
Publisher: Acclaim Entertainment
Platform: Nintendo Entertainment System
Release: January, 1990
Genre: Beat Em’ Up

The original Double Dragon game was something that completely blew my mind when I first saw it in arcades back in the late 1980s. When it became available for the Nintendo Entertainment System I saved up for months to bring it home.

On that day, my brother and I rushed into the house, ripped off the plastic, blew as hard as we could into the cartridge slot and then … what the hell is this? No cooperative two-player?

Thank god that years later Technos Japan would redeem the series with what I consider to be one of most essential games of any NES collection: Double Dragon II: The Revenge.

Cooperative Play … and Much More

Double Dragon 2 is of the rare breed of games that can be enjoyed both with a friend or solo – even by today’s standards with games like Halo or Gears of War.

Double Dragon 2 (Two Players)

Equally impressive, especially for the time, is the rich repertoire of moves available to the player. Fans of the series will enjoy the feature that Double Dragon brought to fighting games: The ability to grab your opponent by the hair or collar and whale on them. Yet even here you have several choices at your command: You can kick the bad guy repeatedly, you can toss him over your shoulder, you can elbow drop, and you can “upper kick” – my favorite move that launches your opponent upwards – hopefully into some environmental hazard.

Additionally, Double Dragon 2 introduced a number of well-timed super moves. I never grew tired of jumping into a cyclone kick, landing, and then following up with a high-jump kick …

… that is, if I could pull it off …

But There Are Frustrations

For its greatness, Double Dragon 2 does manage to be an unfairly punishing title at times. The biggest complaint is, sadly, the controls. Being on the NES, the developers had no choice but to somehow map 3 actions (left attack, right attack, and jump) onto 2 buttons. The choice of making jump a simultaneous A + B button press was unavoidable but I often can’t get the timing down right.

For the most part, this is a forgivable flaw, but when combined with the areas of the game where you are expected to platform it becomes a controller-smashing-inducing experience.

Meant to Punch

On many play sessions (yes, with my kid brother) it was these areas where the game broke from its true design (Platforming?! In a fighting game?) that kept both of us from seeing the game through to its end. I don’t mind losing when I have a lack of skill or I make a poor decision but stuff like this can be a real drag.

Still Great Fun

But when focused on fighting it’s difficult for me to think of a better game in the genre. In addition to your fists and feet it can also be fun to have the environment finish off your opponents instead. My favorite is timing my movement and attacks to ditch enemies out of a flying helicopter in Mission 3 – Battle in the Chopper but there are plenty of other ledges and spikes throughout the game that can do the work for you.

Double Dragon2. Off the ledge!

These are the kind of gameplay elements that would make great achievements or trophies on today’s consoles and makes me wish that publishers would take more care in re-introducing us to our best-loved games from another time. Emulation on Virtual Console, PlayStation Network, and Xbox Live Arcade is one thing but I’d love see faithful recreations that give us something more (like online co-op) and Double Dragon 2 would be a great guinea pig for such an experiment.

Until then, I’ll just have to bring the original Double Dragon 2 cartridge (Game Over Videogames is good retailer to find one) to my brother’s house. Too bad he still lives up in Canada, the hoser.

{ 2 comments }