LibGDX Tutorial 11: Tiled Maps Part 1: Simple Orthogonal Maps

16. April 2014

 

If you’ve never used Tiled read this first!

 

In this tutorial part we are going to look at loading orthogonal maps in LibGDX.  Orthogonal basically means “at a right angle to” which is a fancy way of saying the camera is looking straight at the scene.  Another much less fancy word for this style of game is “top down”.  Common examples include almost every single game from the 16Bit generation of consoles such as Zelda or MegaMan.

 

One of the first problems you are going to encounter is how do you create your maps?  One very common solution is the Tiled Map Editor which fortunately I just completed a tutorial on!  This tutorial assumes you know how to generate a TMX file, so if you haven’t be sure to go through the linked tutorial.  Fortunately LibGDX makes it very easy to work with TMX files.

 

First things first we need to copy the TMX and any/all tilemap image files used to your assets folder, like so:

image

You may notice unlike earlier tutorials I am currently using IntelliJ.  With the recent switch to Gradle it is much easier to get up and running in IntelliJ and I massively prefer it to Eclipse.  That said, everything I say is equally valid in Eclipse or IntelliJ and when there are differences, I will point them out.  If you want to get started with IntelliJ read here.

 

Alright, back on topic…

 

Now that you have the map and tilesets in your project, let’s jump right in with the code:

 

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;

public class TiledTest extends ApplicationAdapter implements InputProcessor {
    Texture img;
    TiledMap tiledMap;
    OrthographicCamera camera;
    TiledMapRenderer tiledMapRenderer;
    
    @Override
    public void create () {
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        camera = new OrthographicCamera();
        camera.setToOrtho(false,w,h);
        camera.update();
        tiledMap = new TmxMapLoader().load("MyCrappyMap.tmx");
        tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);
        Gdx.input.setInputProcessor(this);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        tiledMapRenderer.setView(camera);
        tiledMapRenderer.render();
    }

    @Override
    public boolean keyDown(int keycode) {
        return false;
    }

    @Override
    public boolean keyUp(int keycode) {
        if(keycode == Input.Keys.LEFT)
            camera.translate(-32,0);
        if(keycode == Input.Keys.RIGHT)
            camera.translate(32,0);
        if(keycode == Input.Keys.UP)
            camera.translate(0,-32);
        if(keycode == Input.Keys.DOWN)
            camera.translate(0,32);
        if(keycode == Input.Keys.NUM_1)
            tiledMap.getLayers().get(0).setVisible(!tiledMap.getLayers().get(0).isVisible());
        if(keycode == Input.Keys.NUM_2)
            tiledMap.getLayers().get(1).setVisible(!tiledMap.getLayers().get(1).isVisible());
        return false;
    }

    @Override
    public boolean keyTyped(char character) {

        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        return false;
    }
}

 

When you run the code you should see your map.  Pressing the arrow keys will scroll around the map ( and show bright red when you’ve moved beyond the extents of your map ) .  Pressing 0 or 1 will toggle the visibility of each of the two layers in your map.  ( See the tutorial on Tiled if that makes no sense ).

 

image

 

The impressive thing here is how little code was required to accomplish so much.  In a nutshell it was basically just this:

 

camera = new OrthographicCamera();
camera.setToOrtho(false,w,h);
camera.update();
tiledMap = new TmxMapLoader().load("MyCrappyMap.tmx");
tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);

 

We create an OrthographicCamera, set it to the dimensions of the screen and update() it.  Next we load our map using TmxMapLoader.load() and create a OrthogonalTiledMapRenderer passing in our tiled map.

 

In our render method:

camera.update();
tiledMapRenderer.setView(camera);
tiledMapRenderer.render();

Basically update the camera ( in case we moved it using arrow keys ), pass it in to the TiledMapRenderer with setView() and finally render() the map.  That’s it.

As you can see in our key handler:

 

@Override
public boolean keyUp(int keycode) {
    if(keycode == Input.Keys.LEFT)
        camera.translate(-32,0);
    if(keycode == Input.Keys.RIGHT)
        camera.translate(32,0);
    if(keycode == Input.Keys.UP)
        camera.translate(0,-32);
    if(keycode == Input.Keys.DOWN)
        camera.translate(0,32);
    if(keycode == Input.Keys.NUM_1)
        tiledMap.getLayers().get(0).setVisible(!tiledMap.getLayers().get(0).isVisible());
    if(keycode == Input.Keys.NUM_2)
        tiledMap.getLayers().get(1).setVisible(!tiledMap.getLayers().get(1).isVisible());
    return false;
}

 

Navigating around the map is simply a matter of moving around the camera.  We move in 32pixel chunks because those are the size of our tiles.  So basically we move the camera left/right/up/down by one tile each time an arrow key is pressed.  In the event the 0 or 1 key are pressed we toggle the visibility of that particular layer.  As you can see, you can access the TileMap layers using the getLayers().get() function.

 

In the next part we will look at adding some more complex functionality.

 

On to part two.

Programming , , ,




A quick look at Tiled. An open source 2D level editor

15. April 2014

 

One very common requirement for even the most simple game is a level editor.  The level of sophistication required varies massively from game to game but a lot of the functionality is pretty common.  At the very base level, you need a tool to layout the graphics that make up your world.  Slightly more advanced, you need to define layers, properties and collision volumes.  Often people roll their own solution but you certainly don’t have to.  One very popular 2D level editor is Tiled Map Editor which exports in TMX format, perhaps the most supported 2D game format ( Cocos2D, LOVE, LibGDX and many others all support TMX out of the box ).  As I am going to be writing a tutorial about using tiled maps in LibGDX, I figured I would give a quick introduction to Tiled first.  Keep in mind, we are only going to scratch the very surface of what Tiled is capable of.

 

First off, download and install Tiled.  It has binaries available for Windows and Mac and a source (and daily builds) release available for Linux.  You can download Tiled here.  The documentation is available here.

 

The Tiled UI is pretty straight forward, although it looks quite different across platforms.  Today I will be using the MacOS version.

 

T1

 

A tiled map is fundamentally simple.  You are basically making a grid of tiles.  A tile is a fixed size image within a larger image.  The larger image is called a tile sheet.  It’s somewhat like working with legos to make a level.  Here is an example tilesheet ( taken from here ):

 

Tilesheet

 

It’s a 512x512 image composed of a number of tiles that we are going to paint our level with.

 

Now that we have our tiles, let’s create our map.  Tiled has the ability to create Orthogonal ( straight on or “top down” perspective maps ) or IsoMetric ( angled perspective ).  In this example we are creating a Orthogonal map.  Next you need to decide how many tiles your map consists of in each direction.  Yes, tiled maps are always rectangular in shape.  Finally you need to decide your tile dimensions in pixels.  Looking at the tile map above it isn’t clear how large each tile is, but that is because some of the larger constructs are actually composed of a number of tiles.  You will see how that works in a few seconds, for now simply select 32x32 pixels for tile size and 32x32 tiles for map size.  In real pixel terms, this makes our map 1024 pixels by 1024 pixels.

 

T2

 

Now we need to load our tile set into Tiled. Select Map->New Tileset

 

T3

 

Now in the resulting dialog name it and otherwise we keep the defaults.  Our tile set is made up of 32x32 tiles, so those values work.  The background colour is used if you use a particular colour colour to mark transparency.  In this case we are using the alpha channel to determine transparency, so we don’t need to set a colour value.

 

T4

 

Now if you look at the bottom corner of Tiled you will see a grid of tiles available.  You simply select a tile, then paint in the right window with it.  

 

T5

 

Let’s start by quickly paint our entire map with a grass tile.  Click a grass tile in the tile sets window, like so:

 

T6

 

Now in the left hand window, select the Fill Tool ( or hit F ), then click in the window, and it will be filed with the tile selected filling our level with a nice grass base.

 

T7

 

Now lets say we want to quickly fill in some roads.  The road tile is actually composed of four separate tiles.  This is easily handled in Tiled, simply click the top left tile in the tile set window, then holding SHIFT, click the bottom left, like so:

 

T8

 

Now you can draw with all four tiles at once by simply clicking on the map.  First select the Stamp tool, then draw out the tiles as you desire:

 

T9

 

So, what about the tiles with transparent sections like these ones?

 

T10

 

Well these are designed to be layered over top of other tiles.  Which leads us nicely to layers.  If you have ever used Photoshop or GIMP, you probably already have a pretty good understanding of layering.  Basically layers are drawn over top of lower layers.  So for example, what you draw in Layer 2 is drawn over top of what you draw in Layer 1.  

 

Right now, we only have a single layer, let’s add another one.  In the top menu, select Layer->Add Tile Layer.

 

T12

 

Now in the Layers panel you should see a second layer available.  Clicking the checkbox to the side of the layer shows/hides it’s contents.  Clicking the layer itself makes it active.  Click Tile Layer 2.

 

T11

 

You can now paint “over” the grass and road layer, like so:

T13

 

Congratulations, you’ve just created your first map.  Now we simply save it.  

 

T14

 

 

Next we will take a look at using this map in code in LibGDX.

Programming ,




Maya LT 2015 coming to Steam next week

14. April 2014

 

This press release just arrived from Autodesk:

 

Autodesk Maya LT 2015 to Launch on Steam

 

Today Autodesk announced that Maya LT 2015 is coming to Steam, Valve's popular entertainment platform. Maya LT brings its powerful animation and modeling feature set to Steam's active community of over 65 million gamers, developers and artists to help them create 3D game assets to personalize their games and bring them into popular Steam titles like "Defense of the Ancients 2" (DoTA 2) or to create assets for use in their own games.

"The Valve community is unique, because it includes a very engaged mix of both gamers and developers working together to mod titles and generate content. We hope Maya LT will further that creative spirit and help a Steam user of any skill level to create high quality 3D game assets," said Frank Delise, imagedirector, games solution, Autodesk. "We're engaging with the community on day one by participating in forums, answering questions and offering custom tutorial content for DoTA 2 fans. We can't wait to try new things with the community and see how they push Maya LT to its limit and beyond."

A unique solution for professionals and hobbyists alike, Maya LT boasts a targeted feature set developed from the ground up for the indie game industry, like powerful modeling tools to help create and alter 3D assets of any size and a simplified workflow with the Unity 3D Engine. When purchased on Steam, developers will have access to a full commercial Maya LT license, allowing assets created in the tool to also be exported for use in any game on PC, console and mobile.

An online entertainment platform, Steam hosts over 2000 games in all genres. Users can not only instantly download and play games, but also create and share content through the Steam Workshop.

Available April 22, 2014, Maya LT term licenses will be available monthly for $50 USD and will be available in select countries. To learn more or purchase the product on Steam, visit: http://store.steampowered.com/app/243580 .

To check out all the custom DoTA 2 content and Maya LT 101 tutorials, visit the Autodesk Steam community hub: http://steamcommunity.com/app/243580/ .

 

Steam is quickly becoming the online hub for game development tools.  Maya LT is becoming much more feature complete from when it was originally released, much of it based on user feedback.

News ,




Project Anarchy v2014.0.5 released

10. April 2014

 

Somehow missed this announcement in the chaos of the last few weeks.  It was only via this comment I became aware of the release.  Anyways Havok have released a pretty massive update to Project Anarchy, their free for mobile, cross platform gaming engine.  The star of the release is integration of Autodesk BEAST lighting solution and a new water system, but that’s only a small part.  Post below verbatim is the contents of the release:

 

We are happy to announce the release of Project Anarchy v2014.0.5. It is now available to download. This release contains a host of new features and improvements. The v2014.0.5 release also adds Autodesk® Beast® as a fully integrated component at no charge and includes a new mobile water shape.

Additionally, you can find a number of usability improvements for vForge such as better gizmos and a new transform panel. For easy and quick prototyping we have added several primitive assets that are directly shipped with the Project Anarchy package.

Below you’ll find some highlights for the changes in v2014.0.5. For a full list of changes please take a look at our documentation.

Autodesk Beast Plugin

With Project Anarchy v2014.0.5 we include our integration of the powerful global illumination lighting solution Autodesk Beast.

With Beast, you can generate amazingly realistic lightmaps and lightgrids directly from within vForge, and even distribute the computation workload among multiple machines using DistriBeast. The features of Beast can be considered as a superset of the default vLux integration. Summarized, it has the following strengths when compared to vLux lighting:

  • Faster computation times that scales well on n-cores and in some cases orders of magnitude faster if global illumination is enabled
  • Support for new light shapes: window light, area light
  • Tighter packing on lightmaps to save texture memory
  • Realtime preview through eRnsT tool
  • Better scalability for larger scenes with its support for instanced geometry

The Beast integration can be used for free in the context of Project Anarchy.

In order to activate Beast, open any scene, go to the menu Lighting->Active Lighting Tool and checkmark “Autodesk Beast”. Once this is done Beast will be used when you re-calculate the lighting.

New Mobile Water Shape

A specialized mobile water shape has been added in v2014.0.5. This shape implements specially optimized water rendering for mobile devices. For more details see "Mobile Water Introduction" in the Project Anarchy documentation.

The mobile water shape is located in the effects shape section and can be added to your scene by dragging and dropping an instance of the mobile water shape from the shape creator panel.

New Search Bar in Shape Panel

There is now a search bar in the Shape panel that can be used to filter all objects by name.

Asset Browser Improvements

  • The path to a file can now be copied from the asset browser.
  • When Perforce is used assets can now be checked out directly.

  • Particle Effects are now shown in the asset browser and can be added to the scene via drag & drop.

  • Static meshes are now also shown while dragging them from the asset browser into the scene and snap-to-grid is now also working while dragging meshes into the scene.

New primitive meshes for easy prototyping

In the base data directory there are now some primitive meshes that can be used for quick and easy prototyping and blocking out of a level. Material sets are also available to facilitate color coding sections. On a static mesh instance, see the properties, there is a property called 'CustomMaterialSet', which contains variants for different colors.

New Transform Bar

We have added a 'transform bar' to the bottom of the viewport. The transform bar allows quick and easy changing of the position, rotation and scaling of selected objects. Values can be input both relative to the current value, or absolute.

New Script List Panel

There is now a 'Script List' panel, which shows all the scripts that are used in the scene. You can open the scripts in the script editor directly from that list and you can see which shapes use that list and select them.

vForge Grid Improvements

The grid in vForge has been improved with a number of visual and UX improvements:

  • In ortho mode it now consistently displays in the viewing plane and the grid gets less detailed when zooming out.
  • Lines can be highlighted at user-defined regular intervals.
  • In perspective mode the grid now follows the camera and the grid size is fixed.

Improved Gizmos and ‘Stick to Ground‘ Feature

  • The 'Stick to Ground' feature for the move gizmo has been improved significantly. It can now correctly handle indoor levels comprising of different stories or levels.

  • The scaling gizmo has been improved. Scaling is now much smoother and the center handle of the gizmo now does uniform scaling dropping the need for an extra mode.
  • The translation gizmo now shows helper lines to make it easier to place objects.

General vForge Improvements

  • In the Visual Shader Editor, you can now zoom in with CTRL+Mousewheel.
  • vForge now automatically makes a backup of the scene when entering Run-in-Editor or Play-the-Game mode. Should that crash the editor, on the next start vForge will prompt to use that backup or continue.
  • The multi-user editing dialog will now retrieve more descriptive errors from Perforce in case connecting or workspace resolving fails.

Scaleform Integration Improvements

  • The access to the ActionScript state has been refactored.
  • The new VScaleformValue and VScaleformVariable classes now also allow invoking functions and accessing class members.
  • As opposed to VScaleformValue, an instance of the VScaleformVariableclass represents an ActionScript variable and its value is always kept in sync with the value in the movie.

General Improvements for Programmers

  • Double Tap via remote input is now supported.
  • Cubemap Textures that use the PVR format are now loading correctly.
  • The depth-fog settings are now exposed to Lua, so they can be changed at runtime from script.
  • There is now a new function on the ragdoll component to apply a force or impulse to bones that are inside a sphere. This can be used to create explosions and other effects that push or pull objects within a defined area.

News ,




A look inside Unreal Engine 4

8. April 2014

 

Unreal shook the indie game developer world up recently when they announced they made Unreal Engine 4, with complete source code, available for $19/month as well as a 5% royalty.  I assume some of you are wondering what your 20 bucks a month gets you.  Well this post is intended as an overview of what is included in Unreal to help you decide if you will take the plunge.  By no means is it intended as a review, although I will make a few comments about quality where applicable.  Alright, lets jump right in!

 

Welcome to the Unreal Portal/Getting Started

 

Once you’ve signed up, entered and confirmed your credit card information, you will now be able to access the Unreal Engine portal.  This is where you can go about downloading Unreal Engine and access the community, wiki, source code and documentation, more on that later.

image

 

Click the download link to the right to download the downloader.  This initital download is quite small but that’s only just the beginning.  Now the proper download begins.

Unreal2

 

The initial download is about 7GB, the first patch was 4GB.  Fortunately download speeds are great, even on day 1 I got enough bandwidth to max on out 50MB connection.

 

Each time you launch UE4, you will be prompted for credentials.  ( Haven’t used Offline mode yet, so you shouldn’t require an online connection like CryEngine ).

image

 

Then once again back to the launcher.  This is a combination of news, community portal, marketplace and quick launch.

image

Coincidentally, in Windows 8.1, for some reason none of the news links actually work for me.  You can see down the left hand side there are a number of projects listed under My Content.  Most of these are actually freely available templates you can get from the marketplace.  Each of these is a one level game demonstrating a different concept, be it 2D, 3D, Blueprints, C++ coding, etc.  They range in size between 20MB and 800MB.  They are found in the marketplace:

 

image

 

There’s tons of high quality starter content here and right now almost the entire thing is free.  However, you can see the beginnings of a Unity style marketplace is planned if you look under the coming soon section, you can see a gun based asset pack that is going to be for sale:

image

 

Hopefully this is opened up to the community and becomes a viable competitor to Unity’s Asset Store.  Now let’s fire up the main editor.  See that big yellow LAUNCH button, yeah, that’s how.  I’ll open it up with the Strategy Game template, on of the more complex samples.

 

The Main Editor

 

This is where the magic happens and in a word, it’s polished.

image

 

Perhaps most impressive, notice the Play button in the top toolbar. at any time you can actually hit this and run your game directly in the editor instantly.

 

One word of warning here.  You level is basically running as a game in your engine at all times.  For most people this isn’t going to be a big deal, but to people like myself who develop on the go using a laptop it can be crippling if you arent near a plug.  The Unreal Engine is an absolute battery killer.  On my Windows laptop I can generally run Unity for 3 or 4 hours on battery, a bit longer if I try to stretch it out.  Unreal Engine on the other hand…

 

image

 

Ouch.  My 2013 Macbook Air faired even worse.  It went from fully charged to dead in just over 30 minutes.

 

That leads to an interesting question… how is performance, what kind of system do you need to use Unreal Engine?

 

Well the good news is you don’t need a ton of power, the tools actually ran on the Macbook Air, a 2013 Intel HD4000 GPU powered machine.  That said the experience certainly wasn’t ideal.  In all honesty, if that was my primary machine I would look elsewhere for an engine.  However on my primary Windows box, a Razer Razerblade 14” laptop ( i7, 8GB, nVidia 765m ) the performance is great, except of course the battery drain that is.

 

The editor itself is mostly for content placement, but there is a ton of power packed away.  Most tasks open up a dedicated editor of their own.  It keeps things uncluttered, but isn’t very alt + tab friendly for some reason.

 

Placing content is mostly a matter of drag and drop from the content browser to the scene.  Speaking of Content Browser, here it is:

image

Makes it easy to logically organize all your various game assets.

 

On the right hand side of the editor is the context sensitive details panel as well as a searchable scene graph.

image

 

For level editing, UnrealEd has it’s roots as a CSG ( Constructive Solid Geometry ) editor and that functionality is still there.  Basically CSG modeling works by creating complex shapes by adding and subtracting simple shapes, here for example is a box cut from another box in the editor:

image

These days however, CSG modeling is rarely used, but can be used to quickly prototype a level.

 

Of course there is a height mapped landscape editor built in:

image

You can push/pull the landscape to manipulate it, use brushes to quickly instance geometry and texture the landscape.  OF course you can still drag/drop from the Content Browser to a landscape you’ve generated.

 

This of course only scratches the surface of what the Editor can do.  You can also define lighting, environmental effects, Nav mesh volumes, etc.

image

 

The Editor itself could no doubt fill a book, or perhaps many, but Unreal have done a very good job of compartmentalizing the details.  Until you need something, it’s mostly out of your way, and if you’ve worked in Unity or any 3D applications, it should become pretty quickly intuitive to you.  One thing I really don’t like however is the hold control to do model.  So for example, if you want to paint the geometry, you need to hold down the Ctrl button while left clicking.  It is counterintuitive to me.

 

Remember how I said earlier that the editor is composed of a number of different windows.  One such window is for editing Blueprints.   Let’s take a look at that next.

 

Blueprints

 

So, what exactly are blueprints?  Well if you’ve used prior Unreal engines, it is the replacement for Kismet.  If you are completely new to Unreal, think of Blueprints like a visual programming language.  It works a lot like the graphing functionality in most 3D applications.  Don’t dismiss Blueprints early either, they are surprisingly capable.  Many of the sample games you can download are implemented entirely in Blueprints.

 

Blueprints can be accessed with the Blueprints button in the main interface:

image

 

Each level can have a Blueprint that responds to a variety of events or you can create Class Blueprints, which are basically exactly like C++ classes, except they are implemented as Blueprints.

 

Blueprints open as a completely separate window, like so:

image

 

Blueprints can be complex beasts.  Here for example is the Blueprint for controlling the character from the blueprint example:

image

 

One annoyance I have is the lack of zoom granularity control.  Zooming to fit just what you want on the screen can be a chore as you under/over-zoom due to the lack of granularity.

 

Think of Blueprints like massive flow charts that control, well, just about everything in your game.  Most classes and their properties in the game are exposed as Blueprints and you have a large library of functionality available to you.

image

 

This post is starting to get a bit long so I am going to split it into two parts.  In Part Two we look at the C++ programming side of the fence, explore the documentation available, take a look at the source and the community available.

 

On to part two.

Programming , ,