Creating dynamically equipped characters in 2D and 3D games

9. January 2014

 

Right off the hop for my new game I have to deal with a problem that many games have to deal with but one that could have a huge impact on how my game is structured, so I am going to address it with a proof of concept right up front.   That thing, as the title probably spoils, is character customization.

 

As I said earlier, this is a pretty common problem in games and something you see questions about quite often if you hang around game development forums for any period of time.  So what do I mean with character customization?  Ever played Diablo or a similar title?  When you change your gear in Diablo, your character is updated on screen.  This behaviour is pretty much expected in this day and age… personally I really hate when I am playing an RPG and the weapon I equip has no affect on my avatar.  That said, it is certainly a non-trivial problem and one that could have a pretty big impact on your game.

 

Let’s start by taking a look at the various options… at least the ones I can think of.

 

2D - Pre-render all possible configurations

Of course, brute forcing it is always a possibility and in a few cases may actually be ideal.  Basically for a 2D game, you simply create every combination of sprite for every combination of equipment.  So if you have an animation sequence for “walk_left” and “walk_right”, you would have to create a version for each possible equipable item.  So you might have “walk_left_with_axe” and “walk_left_with_sword” sprite sheets for the different weapon combinations.  If you are rendering your spritesheets automatically from a 3D application, this could actually be the easiest approach.  Of course there are some seriously massive downsides to this approach.  Memory usage quickly becomes outrageous.  For each piece of equipment you double the size of your original sprite sheet for example.  Once you start adding more and more options, this approach quickly becomes unfeasible.  If you only have a very small amount of customization ( two or three weapon options ), this approach may appeal due to it’s simplicity.  With anything more than a couple combinations though, this approach is pretty much useless.

 

2D – Pre-rendered spritesheet + pre-rendered weapon animation frames.

You can use a regular sprite sheet and simply keep the weapons separate.  So basically you have two separate sprite sheets, one of the character without weapons, one with just the weapons.  Then at run-time you combine them.   Consider these two sprite sheets ( taken from a StackOverflow question ).

Animated Character:

Player SpriteSheet

Weapon:

Weapon SpriteSheet

Then at run-time you combine the two sprites together depending on what is equipped.

In fact, if your weapon isn’t animated ( as in, it doesn’t move, like a sword, as opposed to a weapon like a whip or nunchucks ) you can get by using a hard point system, where you define the mount position of the weapon ( for example, the players right hand ) and orientation.  Basically for each frame of animation, you provide an x and y coordinate as well as rotation amount that represents where and how the weapon should be mounted.  Then at runtime you combine the two sprites, positioning and rotating the weapon sprite relative to the mount/hardpoint. This way, you only need a single image per equipable weapon.

This approach has a couple downsides.  First, you need a separate data file to hold mount point data and possibly a tool to generate it.  Second, it makes bounding/hit detection more difficult as the mounted weapon may exceed the dimensions of the originating sprite.  Third, you need to deal with z-depth issues, you cant simply paste the weapon on top of the sprite, as what happens when the character is walking right but carrying the weapon in the left hand?  To handle this your workflow needs to basically be: render obscured weapons, render character sprite, render foreground weapons.  Finally, weapons with their own animation, like a whip snapping, would require even more effort.

All told, this is probably the easiest while still flexible system for 2D animation.  It requires a bit more work than simply brute forcing your sprite sheets, but the payoffs in reduced size and complexity are well worth it, especially if you have more than a couple items.  One other big win about this approach is then weapons can be re-used across different sprites, a huge win!  Then you can model a single sword and it will be available to all sprite sheets with hard/mount point information available.

 

3D - Bone/hardpoint system

If your game is pure 3D this is often the way you want to go.  If you character is a knight for example, in your 3D modelling application you create named hard points in your model, either as bones or as an object of some form such as a null object, point or invisible box.  Then at runtime you bind other models to those locations.  So for example, if you equip a long sword and shield, your code searches for the “right_arm_shield” bone and uses it as the parent object for a shield 3D model.  Then you bind a sword to say… the “left_arm_hand” bone.  You can see an example of this behaviour in this UDK example.

This approach is basically identical to the last 2D method mentioned except in 3D and that you dont generally need to define your own hardpoint system, as most 3D packages and engines already support it out of the box, either by binding to a bone or by accessing and parenting 3D objects to named locations.  Like working in 2D, then your weapon and character are two separate entities, like so:

3P_Weapon_Attach.JPG

One of the major advantages of 3D over 2D is flexibility.  Most animations in 2D need to be pre-calculated, while in 3D you have a great deal more flexibility with the computer filling in the blanks for you.  Unlike in 2D, additional 3D animations add very little to the data file sizes.

 

2D Bone based animation

One of the major downsides to 2D animation is, as you add more animations, it takes up more space.  People have been working on solutions, one of the most common of which is 2D bone animation.  How exactly can you use bones on a 2D image file you ask?  That’s a good question!  In 3D, its pretty simple… the motion/influence of the bone transforms the attached geometry.  In 2D, there is no geometry, so how can you do this?

Well, the simple version is, you cut your bitmap or vector image up into body parts.  So instead of a single image of an animated character, you instead of an image for the foot, lower leg, upper leg, torso, waist, shoulder, left upper arm, etc…  Then you can draw 2D bones that control the animation of this hierarchy of images.  There are applications/libraries that support this, making it mostly transparent for you.  Here is one such example from Spine from Esoteric Software.

 

The character:

Creating Bones

 

It looks like a single image ( and you can see a couple bones being drawn in the foot/leg area ), but it is actually composed of a few dozen source images:

Set Parent

 

Basically the workflow goes, you create your traditional image in your regular art program, except instead of creating a single image, you create dozens of hopefully seamless ones representing each body part.  You stitch them together, setting the drawing order ( what’s covering what ), then define bones to create animations.  This has the double advantage of massively decreasing space requirements while simplifying the animation process.  The downsides are creating your initial image are a great deal more difficult and of course, you need to buy ( or roll your own ) bone system, such as Spine. 

 

Spine is not the only option, there is also Spriter from BrashSoftware and probably others I am unaware of.  Both of these are commercial packages, but then, both are dirt cheap ( IMHO ) with price tags between $25 and $250 dollars, with $60 and $25 dollars being the norm with each package respectively.

The nice thing about taking this segmented bone approach… you basically get the ability to swap components or bind weapons for free.

 

2.5D hybrid approach

2 1/2D is becoming more and more popular these days.  Essentially a 2.5D game is a 3D game with 2D assets ( such as 2D sprites over a 3D background ), but more commonly its 3D sprites over a 2D background.  How does this work?

Well there are two basic approaches.  You model, texture, animate your 3D model as per normal.  Any character customization you perform you would do as if you were working in full 3D.  Now is where the two different approaches vary, depending on performance, the hardware you are running on, etc…  You can either generate a sprite sheet dynamically.  Essentially when your character is loaded or you change equipment, in the background your game renders a sprite sheet of your updated character containing every animation frame, then you use this sheet as if it was a normal 2D sprite sheet.  The other option is, you render your character each time it moves.  Creating a spritesheet consumes more memory, but very little GPU or CPU demand.  Generating your characters current animation frame dynamically on the other hand, takes almost no memory, but at a much higher CPU/GPU burden.  Which is right for your game is obviously up to you.

Of course the 2.5D approach certainly has it’s share of problems too.  First off, it is the most complicated of the bunch.  Second, you cant do any “by hand” calculations on your generated sprite/spritesheets, as they are now being rendered dynamically.  This means no ability to create pre-calculated bounding volumes for example.  On the other hand, the 2.5D approach gives you most of the advantages of 3D ( compact animation data structure, easy programmable modification, ability to alter texture mapping, lighting effects, etc… ) that 3D does, but with the simplicity of dealing with a traditional 2D world.

One animation to rule them all!

You may be thinking WAHOO… I can cut my work way down now!  All I need to do is animate an attack sequence and then I can simply substitute the different weapon images.  Not so fast I am sorry to say.  Think about it this way…  are the images for swinging an AXE and a Sword the same?  What about a pole arm?  You are still going to have several different animations to support different classes of weapons, but these techniques will still vastly reduce the amount of data and work required while allowing a ton of customization.

 

 

So then, what am I going to do?

So, which approach am I taking?  Ultimately I am going to require a great deal of customization, going far beyond the examples described above.  One such example scenario is a Mech with a customizable left weapon… this weapon could be an arm holding a gun, a turret containing one or more guns, or possibly even a large pack of rockets.  Each “weapon” could have it’s own animation set.  Oh, and I am much more proficient in 3D than 2D.  On the other hand, the game itself is a 2D game and I would prefer to keep it that way for the simplicity that brings in a number of areas ( level creation tools, path-finding and other AI tasks, physics, cheating at art, etc… ).  As a result, I am going to try the 2.5D approach, where the mech is created and animated in 3D, dynamically equipped, then rendered to 2D.  I am going to try both pre-rendering sprite sheets and dynamically rendering a single frame and see what the overhead of each is.  I actually have the compounded issue of dealing with enemy characters that are also dynamically generated, so any impact will be magnified many time over!

If I can’t get adequate performance from each approach, I may be forced to go full 3D and emulating a 2D look.  As I said, it’s one of those things that can have a major impact on your game!  That said, I am pretty confident performance wont be too much of a factor.  My immediate take away task list is:

  • get a LibGDX project set up that can load and render an textured, animated 3D model exported from Blender. I am pretty new to 3D in LibGDX ( okay… completely new to it )
  • bind another model to a bone on this model ( aka, a sword to a hand bone )
  • try to dynamically generate a sprite sheet of the character’s complete animation.  Measure resulting memory usage and time required to generate sheet
  • re-architect the code to instead generate each frame of animation per frame on demand.
  • scale both scenarios up to include multiple instances and see results on performance
  • measure performance impact of each approach on both desktop and mobile.

 

The outcome of this experiment will ultimately decide what approach I take.  Stay tuned if that process sounds interesting!

 

Oh, and of course, these are only the scenarios I could come up with for dealing with dynamically equipped characters, if you have another idea, please share it!

Design, Programming , , ,




Leadwerks “indie edition” Game Engine added to steam for $99

6. January 2014

 

It started with GameMaker, now it seems more and more game development packages are being added to Steam, generally at vastly discounted prices.  Today we see Leadwerks Game Engine: Indie Edition has been added for $99.  On the website, Leadwerks is $199.  The question is, what is the limitiation of “indie edition”?  That’s the million dollar question.  It’s not a distribution thing, as they say in the Steam entry:

Your games you make are yours. Yours to play, yours to sell, yours to give away, and do as you please. You will never be charged royalties for any game you make in Leadwerks.

 

Anyways… about Leadwerks

Image Source

 

Leadwerks is a powerful and easy-to-use game engine for building any kind of 3D game. With a rapid development pipeline, Lua script integration, and plenty of learning materials, Leadwerks is the perfect way to make 3D games that look and feel amazing. Get started today making your own 3D games for Steam.

Key Features

Learn to Make Your Own 3D Games
We provide tons of documentation and video tutorials walking you through the steps to build your own 3D games. Leadwerks is the perfect pathway to go from total noob to pro game developer.


Advanced Graphics
Leadwerks brings AAA graphics to the masses, with hardware tessellation, geometry shaders, and a deferred renderer with up to 32x MSAA. Our renderer redefines realtime with image quality more like a cg render than real-time games of the past. The use of OpenGL 4.0 provides equivalent graphics to DirectX 11, with cross-platform support across operating systems, for future expansion.


Built-in Level Design Tools
Build game levels from scratch right in our editor with constructive solid geometry. Our tools make it easy to sketch out your design and bring your ideas to life. Anyone can build their own game worlds in Leadwerks, without having to be an expert artist.


Integrated Lua Script Editor
We integrated Lua right into Leadwerks because of its proven track records in hundreds of commercial games including Crysis, World of Warcraft, and Garry's Mod. Lua integrates seamlessly with native code for rapid prototyping and instant control. The built-in debugger lets you pause your game, step through code, and inspect every variable in the program in real-time. Lua is perfect for beginners, and the integrated Just-In-Time (JIT) compiler ensures your games will keep running fast as they grow.


Visual Flowgraph for Advanced Game Mechanics
Our unique visual flowgraph enables designers to set up game mechanics, build interactions, and design advanced scripted sequences, without touching a line of code. The flowgraph system integrates seamlessly with Lua script, allowing script programmers to expose their own functions and add new possibilities for gameplay.

 

Personally, I’ve no experience with Leadwerks, so I can’t comment on what the engine is like.

 

editFound this post, with a bit more details on the limitations of Steam, sorta…

"Leadwerks: Indie Edition" will be launched on Steam January 6th.  This will be on Windows only, with support for Lua scripting.  The following groups will receive a free Steam key to add this product to their Steam account:

  • Leadwerks 3.0 customers who pre-order the upgrade to version 3.1.
  • New customers who pre-order Leadwerks 3.1.
  • All Kickstarter backers who backed Leadwerks for Linux for $49 or more.  (Even if you don't run Windows, hold onto this as the Linux version on Steam will have special features.)

Leadwerks 3.1 for Linux and Windows will be released together next, with the exact release date to be determined.  Leadwerks 3.1 for Mac will follow this, with mobile add-ons for iOS and Android coming last.  (There is no purchase necessary to upgrade the mobile add-ons from Leadwerks 3.0 to Leadwerks 3.1.)

 

Still not completely sure what that means in terms of limitations… does that mean the Indie edition is Lua only and targets only WIndows?  Or just that the Windows version is available?

 

edit2: Found this comment on the difference:

The standard edition is more expensive but includes C++ programming capability. That's important to some people, and for others it's not a big deal. Since we use a just-in-time compiler to make Lua execution fast, Lua alone is perfectly capable of making full games.

So, indie edition has no C++ support…  that’s a bit of a big difference to many people I should imagine.

News, Programming




Godot Unity like game engine going open source

5. January 2014

 

There is a new entrant in the game engine space, the Godot game engine from Okam Studio.  The engine was apparently used for in-house projects and is over a decade in the making.  The editor runs on Linux, Windows and OSX and can target desktop, mobile, consoles as well as HTML.

godot1

godotss2.png

godotss1.png

 

From observation, the engine appears to be similar to Unity, but powered by C++.  It uses a custom scripting language that appears LUA like.

 

In the developers own words:

We’ll be opening a game engine that has more than a decade of work (and several iterations) as MIT license soon.

It’s not an engine made by hobbyists, this is a production tool used to develop and publish plenty of games for PC, Consoles and Mobile. It’s currently in beta stage, meaning it’s feature complete and fully usable, but lacks very little fine tuning and testing. It has a similar feature set to Unity (little less stuff on 3D front, much more stuff on the 2D front, debugging). and runs on all the popular desktop and mobile platforms, as well as on the web (through asm.js).

Unlike almost any other game engine with this level of features, the editor runs fine in Linux, as well as Windows and OSX, and supports one click deploy.

 

Apparently the engine is being released under the MIT open source license ( a very generous license ) and is undergoing polish before complete release.  If you are interested in early access, contact juan@okamstudio.com.

 

I’ll be keep an eye on this one… a C++ powered Unity like engine is sure to be interesting to many.  Not sure exactly when it will drop but for now we are … Waiting for Godot.

 

Ok… that was bad.   More details as I get them.

News, Programming




LibGDX Tutorial 9: Scene2D Part 4–UI Skins

18. December 2013

 

One of the nicest features of Scene2D is the UI layer built over top of it.  Scene2D.ui provides a series of widgets that make creating a UI an breeze, something often lacking in game development libraries.  That said, there is one very confusing stumbling block before you can get to work with UI… Skins.

 

A skin is a collection of files that go together to make up your user interface.

First is a JSON file ( JavaScript Object Notation ), which is a popular JavaScript based data storage format, like XML light.  In the JSON file you describe the various properties of your skin such as how your widgets should look. 

Next is a texture atlas.  We looked at using TexturePacker to make a texture atlas back in the graphics tutorial.  The texture atlas describes the layout of all the images that make up your UI.  This is a .atlas extension file.

Along with the texture atlas, you’ve also got the actual image that TexturePacker generated.

Finally you have the fnt and the associated image.  We covered fonts back in the Hello World tutorial.

 

This can all seem pretty daunting, especially starting from scratch.  Fortunately there is a skin included in the LibGDX tests.  The files you are interested in are uiskin.atlas, uiskin.json, uiskin.png, default.png and default.fnt.  Simply download and place each of these files in the Android assets/data folder of your project.  If you are downloading from the Github link I provided, be sure to download the RAW version of each file!

 

Let’s take a quick look at some of the above files for a better idea of what goes into them.  I will ignore the font files, we already covered that.  The atlas and png file we’ve already covered as well, but here is uiskin.png, so you’ve got some idea what is included:

uiskin

 

These are the various graphics that go in to creating the UI.  Let’s take a look at uiskin.json:

 

 

{
com.badlogic.gdx.graphics.g2d.BitmapFont: { default-font: { file: default.fnt } },
com.badlogic.gdx.graphics.Color: {
    green: { a: 1, b: 0, g: 1, r: 0 },
    white: { a: 1, b: 1, g: 1, r: 1 },
    red: { a: 1, b: 0, g: 0, r: 1 },
    black: { a: 1, b: 0, g: 0, r: 0 }
},
com.badlogic.gdx.scenes.scene2d.ui.Skin$TintedDrawable: {
    dialogDim: { name: white, color: { r: 0, g: 0, b: 0, a: 0.45 } }
},
com.badlogic.gdx.scenes.scene2d.ui.Button$ButtonStyle: {
    default: { down: default-round-down, up: default-round },
    toggle: { down: default-round-down, checked: default-round-down, up: default-round }
},
com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle: {
    default: { down: default-round-down, up: default-round, font: default-font, fontColor: white },
    toggle: { down: default-round-down, up: default-round, checked: default-round-down, font: default-font, fontColor: white, 
    downFontColor: red }
},
com.badlogic.gdx.scenes.scene2d.ui.ScrollPane$ScrollPaneStyle: {
    default: { vScroll: default-scroll, hScrollKnob: default-round-large, background: default-rect, hScroll: default-scroll, 
    vScrollKnob: default-round-large }
},
com.badlogic.gdx.scenes.scene2d.ui.SelectBox$SelectBoxStyle: {
    default: {
        font: default-font, fontColor: white, background: default-select,
        scrollStyle: default,
        listStyle: { font: default-font, selection: default-select-selection }
    }
},
com.badlogic.gdx.scenes.scene2d.ui.SplitPane$SplitPaneStyle: {
    default-vertical: { handle: default-splitpane-vertical },
    default-horizontal: { handle: default-splitpane }
},
com.badlogic.gdx.scenes.scene2d.ui.Window$WindowStyle: {
    default: { titleFont: default-font, background: default-window, titleFontColor: white },
    dialog: { titleFont: default-font, background: default-window, titleFontColor: white, stageBackground: dialogDim }
},
com.badlogic.gdx.scenes.scene2d.ui.Slider$SliderStyle: {
    default-horizontal: { background: default-slider, knob: default-slider-knob }
},
com.badlogic.gdx.scenes.scene2d.ui.Label$LabelStyle: {
    default: { font: default-font, fontColor: white }
},
com.badlogic.gdx.scenes.scene2d.ui.TextField$TextFieldStyle: {
    default: { selection: selection, background: textfield, font: default-font, fontColor: white, cursor: cursor }
},
com.badlogic.gdx.scenes.scene2d.ui.CheckBox$CheckBoxStyle: {
    default: { checkboxOn: check-on, checkboxOff: check-off, font: default-font, fontColor: white }
},
com.badlogic.gdx.scenes.scene2d.ui.List$ListStyle: {
    default: { fontColorUnselected: white, selection: default-rect-pad, fontColorSelected: white, font: default-font }
},
com.badlogic.gdx.scenes.scene2d.ui.Touchpad$TouchpadStyle: {
    default: { background: default-pane, knob: default-round-large }
},
com.badlogic.gdx.scenes.scene2d.ui.Tree$TreeStyle: {
    default: { minus: tree-minus, plus: tree-plus, selection: default-select-selection }
}
}

 

If you’ve ever used CSS, this should look immediately familiar.  You are essentially telling LibGDX how to style each class by using the fully qualified Java class name.  Let’s take a look at a particular example we are going to be using shortly, TextButton.

 

com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle: {
    default: { down: default-round-down, up: default-round, font: default-font, fontColor: white },
    toggle: { down: default-round-down, up: default-round, checked: default-round-down, font: default-font, 
fontColor: white, 
    downFontColor: red }
}

 

You are setting the values for the class TextButtonStyle or on of the classes it is derived from.  You may notice for fontColor, “white” is passed.  If you look up in the skin, you can see how its defined:

com.badlogic.gdx.graphics.Color: {
    green: { a: 1, b: 0, g: 1, r: 0 },
    white: { a: 1, b: 1, g: 1, r: 1 },
    red: { a: 1, b: 0, g: 0, r: 1 },
    black: { a: 1, b: 0, g: 0, r: 0 }
}

 

You can see “white” is a Color with the values 1/1/1 for rgb and 1 for alpha… in other words, white Smile

The other key thing is the value for down.  As you can see from the TextButtonStyle, down is a Drawable.  The value specified, default-round-down is an entry in the atlas file:

default-round-down
  rotate: false
  xy: 99, 29
  size: 12, 20
  split: 5, 5, 5, 4
  orig: 12, 20
  offset: 0, 0
  index: -1

This is specifying the size and location within the uiskin.png file.  More details about skins can be found on the wiki.

 

Now that you have your skin files, let’s take a look at a sample using Scene2d.ui:

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;

public class UIDemo implements ApplicationListener {
    private SpriteBatch batch;
    private Skin skin;
    private Stage stage;

    @Override
    public void create() {        
        batch = new SpriteBatch();
        skin = new Skin(Gdx.files.internal("data/uiskin.json"));
        stage = new Stage();

        final TextButton button = new TextButton("Click me", skin, "default");
        
        button.setWidth(200f);
        button.setHeight(20f);
        button.setPosition(Gdx.graphics.getWidth() /2 - 100f, Gdx.graphics.getHeight()/2 - 10f);
        
        button.addListener(new ClickListener(){
            @Override 
            public void clicked(InputEvent event, float x, float y){
                button.setText("You clicked the button");
            }
        });
        
        stage.addActor(button);
        
        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void dispose() {
        batch.dispose();
    }

    @Override
    public void render() {        
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        
        batch.begin();
        stage.draw();
        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

 

You run this app and you should see:

image

 

Most of this is pretty familiar at this point.  We create a Skin object and load it using the typical file IO calls.  The file you want to load is the json config, uiskin.json.  This file points to all all of the other files, they will be loaded automatically by the Skin.  Next we create a TextButton, the values passed in to the constructor are the text to display on the button, the skin and the value in the skin to use.  If you look at the entry for the TextButton in the skin JSON file see:

com.badlogic.gdx.scenes.scene2d.ui.Button$ButtonStyle: {
    default: { down: default-round-down, up: default-round },
    toggle: { down: default-round-down, checked: default-round-down, up: default-round }
},

You are saying you want to use the “default” entry.  Coincidentally, if you dont specify anything, default will be used.  We position and size the button and set up a click listener that simply changes the displayed text when the button is clicked.  Now the cool part… UI widgets like TextButton are simply Actors, so they work just like other Scene2D actors, add it to the stage and it’s ready to go.

 

Scene2D ui is a fairly involved topic so I will follow up with a more advanced example next tutorial.

Programming ,




LibGDX Tutorial 3C: Scene management

11. December 2013

 

So far we’ve look at what Scene2D provides in terms of Actors, Actions as well as handling input, now we will look at some of the scene management functionality it provides.  One of the very powerful capabilities of Scene2D is grouping.  Let’s jump right in with an example.  In this example I used these two graphics:

jet(look, there is a space here!)flame

 

By the way, those are two different images.  One is a jet and the second is the engine exhaust.  Let,s take a look at grouping them together in a scene as a single transformable entity, a pretty common game development task.

 

 

package com.me.mygdxgame;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Stage;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;


public class SceneManagementDemo implements ApplicationListener {
    
    private Stage stage;
    private Group group;
    
    @Override
    public void create() {        
        stage = new Stage(Gdx.graphics.getWidth(),Gdx.graphics.getHeight(),true);
        final TextureRegion jetTexture = new TextureRegion(new Texture("data/jet.png"));
        final TextureRegion flameTexture = new TextureRegion(new Texture("data/flame.png"));
        
        final Actor jet = new Actor(){
            public void draw(Batch batch, float alpha){
                batch.draw(jetTexture, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), 
                        getScaleX(), getScaleY(), getRotation());
            }
        };
        jet.setBounds(jet.getX(), jet.getY(), jetTexture.getRegionWidth(), jetTexture.getRegionHeight());
    
        final Actor flame = new Actor(){
            public void draw(Batch batch, float alpha){
                batch.draw(flameTexture, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(),
                        getScaleX(), getScaleY(), getRotation());
            }
        };
        flame.setBounds(0, 0, flameTexture.getRegionWidth(), flameTexture.getRegionHeight());
        flame.setPosition(jet.getWidth()-25, 25);
        
        group = new Group();
        group.addActor(jet);
        group.addActor(flame);
        
        group.addAction(parallel(moveTo(200,0,5),rotateBy(90,5)));
        
        stage.addActor(group);
        
        
    }

    @Override
    public void dispose() {
        stage.dispose();
    }

    @Override
    public void render() {    
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

 

When you run it, you will see:

SceneManagementCompressed

 

As you can see, once grouped, the attached actors inherit any transformations applied to the group.  The code in this example should be pretty straight forward at this point, not much new here.  First we load our two images as TextureRegions.  We then create an actor for each, in both cases setting it’s boundaries with setBounds() or it wont render correctly.  For each Actor we implement the full batch.draw() function to make sure rotation and scaling are properly rendered.  Finally for the flame texture, we set it’s position relative to the jet Actor.

 

Then we create a new Group object, this is the secret sauce behind Scene2D grouping.  Then instead of adding our two Actors to the Scene, we instead add them to the Group, which is then added to the Scene.  So that we can actually see something happening in this example, we apply a moveTo and rotateBy Action to our group.  We covered Actions in the last tutorial post if you want more details.  One important thing I didn’t show here is, it is possible to translate the individual Actors within the Group.

 

One other aspect of Scene2D is determining if a hit occurred.  Back in Scene2D Tutorial Part 1 we saw the touchDown function, which is called when an Actor within a Scene is touched.  Now we will briefly look at the logic driving this process.  The Stage’s hit() method is called, which in turn calls the hit() method of every Actor within the stage.  hit() passes in un-translated coordinates, making the process easier on the developer.  The default hit() method simply checks the bounding box of the Actor…  the following example instead checks the bounding circle… in case you had a say… circular object! Smile

 

package com.me.mygdxgame;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.Touchable;

import java.util.Random;

public class SceneManagementDemo implements ApplicationListener {
    
    // Create an Actor "Jet" that displays the TextureRegion passed in
    class Jet extends Actor {
        private TextureRegion _texture;
        
        public Jet(TextureRegion texture){
            _texture = texture;
            setBounds(getX(),getY(),_texture.getRegionWidth(), _texture.getRegionHeight());
            
            this.addListener(new InputListener(){
                public boolean touchDown(InputEvent event, float x, float y, int pointer, int buttons){
                    System.out.println("Touched" + getName());
                    setVisible(false);
                    return true;
                }
            });
        }

        // Implement the full form of draw() so we can handle rotation and scaling.
        public void draw(Batch batch, float alpha){
            batch.draw(_texture, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(),
                    getScaleX(), getScaleY(), getRotation());
        }
        
        // This hit() instead of checking against a bounding box, checks a bounding circle.
        public Actor hit(float x, float y, boolean touchable){
            // If this Actor is hidden or untouchable, it cant be hit
            if(!this.isVisible() || this.getTouchable() == Touchable.disabled)
                return null;
            
            // Get centerpoint of bounding circle, also known as the center of the rect
            float centerX = getWidth()/2;
            float centerY = getHeight()/2;
            
            // Square roots are bad m'kay. In "real" code, simply square both sides for much speedy fastness
            // This however is the proper, unoptimized and easiest to grok equation for a hit within a circle
            // You could of course use LibGDX's Circle class instead.
            
            // Calculate radius of circle
            float radius = (float) Math.sqrt(centerX * centerX +
                    centerY * centerY);

            // And distance of point from the center of the circle
            float distance = (float) Math.sqrt(((centerX - x) * (centerX - x)) 
                    + ((centerY - y) * (centerY - y)));
            
            // If the distance is less than the circle radius, it's a hit
            if(distance <= radius) return this;
            
            // Otherwise, it isnt
            return null;
        }
    }
    
    private Jet[] jets;
    private Stage stage;
    
    @Override
    public void create() {        
        stage = new Stage(Gdx.graphics.getWidth(),Gdx.graphics.getHeight(),true);
        final TextureRegion jetTexture = new TextureRegion(new Texture("data/jet.png"));
        
        jets = new Jet[10];
        
        // Create/seed our random number for positioning jets randomly
        Random random = new Random();
        
        // Create 10 Jet objects at random on screen locations
        for(int i = 0; i < 10; i++){
            jets[i] = new Jet(jetTexture);
            
            //Assign the position of the jet to a random value within the screen boundaries
            jets[i].setPosition(random.nextInt(Gdx.graphics.getWidth() - (int)jets[i].getWidth())
                    , random.nextInt(Gdx.graphics.getHeight() - (int)jets[i].getHeight()));
            
            // Set the name of the Jet to it's index within the loop
            jets[i].setName(Integer.toString(i));
            
            // Add them to the stage
            stage.addActor(jets[i]);
        }
        
        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void dispose() {
        stage.dispose();
    }

    @Override
    public void render() {    
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

 

 

When you run this app, 10 randomly located jet images will be drawn on screen. 

 

SceneManagement2Compressed

 

As you click each, it will disappear.  One important thing to realize is hit() is evaluated in reverse order objects are created.  So, the last object you add to the stage will be the first one hit() if more than one object occupy the same space.  The determining function whether a Jet has been touched or not is hit().  hit() works by creating a bounding circle to fit the image within, then checking to see if the mouse pointer is within the bounds of that circle.  When a hit occurs, we return the object hit, otherwise we return null.

 

The nice thing about this system is the user doesn’t have to worry about any translations applied to it’s parent or other translations that have occurred.  It’s also important to realize this is a pretty derived example.  If you removed the overriden hit() method, the default implementation would actually work better.  You do NOT need to provide a hit() method in your derived Actor classes unless the default doesn’t fit your needs.  This example is merely to show how the Scene2D hit detection works, and how to implement a custom detector.  Should you wish to say, implement pixel-perfect detection, you could do it this way.  I commented this example a bit more than I regularly do, to explain the bits I’ve glossed over.

Programming , ,