Maps
libGDX can manage and draw different kinds of tiled maps: orthogonal (with square or rectangle tiles), isometric (fake 3D, with diamond tiles) and hexagonal.
Maps can be imported in the TMX or tIDE format, or constructed from a collection of texture regions (see the provided Map_Hexagonal demo).
I suggest using
Tiled or
tIDE to create and edit your maps.
It is also possible to create a texture atlas from an existing map with the TiledMapPacker tool. I recommend using it when you have visual issues while zooming or rescaling the map as it duplicates the edges of your tiles. To create the atlas:
- download the nightly build of libGDX;
- uncompress the file in a folder of your choice;
- run the following command in the installation folder:
java -cp gdx.jar;gdx-natives.jar;gdx-backend-lwjgl.jar;gdx-backend-lwjgl-natives.jar;extensions\gdx-tools\gdx-tools.jar;extensions\gdx-tiled-preprocessor\gdx-tiled-preprocessor.jar com.badlogic.gdx.tiledmappacker.TiledMapPacker %1 %2 %3
%1 = input folder
%2 = output folder (optional)
%3 = --stripe-unused (optional)
How to load a map (TMX format):
Dim TMXLoader As lgMapTmxMapLoader
Dim Maps As lgMapTiledMap
Maps = TMXLoader.Initialize2("maps/MyMap.tmx")
Replace lgMapTmxMapLoader by lgMapAtlasTmxMapLoader or lgMaptIDEMapLoader for the other formats.
The lgMapTiledMap class gives access to the layers, properties and tilesets of the map.
The layers and the tilesets are ordered and indexed, starting by index 0. Example of access to the last layer:
Dim LastLayer As lgMapTiledMapLayer
LastLayer = Maps.Layers.Get(Maps.Layers.Count - 1)
The properties are stored and retrieved by name. Example:
Dim TileDoorX As Int = LastLayer.Properties.Get("doorX")
Maps use special renderers that rely upon SpriteBatch: lgMapHexagonalTiledMapRenderer, lgMapIsometricTiledMapRenderer and lgMapOrthogonalTiledMapRenderer. They are initialized with the map (lgMapTiledMap) as the main parameter and are very simple to use:
MapRenderer.SetCameraView(Camera)
MapRenderer.Render
They can render a selected set of layers (Render2) or a specific layer (RenderTileLayer).
Call the Dispose function of the map and of its renderer when you no longer need them.
Particles
Particles are small graphics objects used in large number to simulate certain kinds of "fuzzy" phenomena, which are otherwise very hard to reproduce with conventional rendering techniques, e.g. fire, explosions, smoke, moving water, clouds, fog, snow, glowing trails, magic spells, etc.
Particles are created with the lgParticleEmitter class. The emitter has many properties that control how each particle behaves: life, velocity, rotation, scale, etc. You can save all these settings to a file with the Save function and reload them with the Load or Load2 function.
Creating a particle emitter from scratch is rather difficult, so I recommend using the Particle Editor, especially since it allows combining multiple emitters to create a complex effect. To run it:
- download the nightly build of libGDX;
- uncompress the file in a folder of your choice;
- run the following command in the installation folder:
java -cp gdx.jar;gdx-natives.jar;gdx-backend-lwjgl.jar;gdx-backend-lwjgl-natives.jar;extensions\gdx-tools\gdx-tools.jar com.badlogic.gdx.tools.particleeditor.ParticleEditor
Online documentation for this tool.
If the file produced by the editor contains more than one emitter, the Load function of the lgParticleEmitter class will load only the first. To load the particle effect, i.e. the complete set of particles emitters, use one of the Load functions of the lgParticleEffect class.
Once loaded, the particle effect has to be stated as ready with the Start function. Although this does not seem necessary in some cases, it is a good habit to take.
The lgParticleEmitter and lgParticleEffect classes render their particles with the Draw function. This function must be inserted between the Begin and End of a SpriteBatch. Since, basically, particle emissions are animations, an emitter needs to know the elapsed time between each frame. Thus, before calling Draw, call the Update function. Or use Draw2 that does the Update and the Draw at the same time.
If you draw repeatedly the same particle effect, the lgParticleEffectPool class provides you an efficient and convenient way of reusing the created instances. With a pool, you can minimize the number of memory allocations/deallocations and avoid triggering the garbage collector too often. You can also limit the number of effects at the same time (the capacity of the pool will not exceed the maximum that you specified).
To learn how to use a pool, see the ParticlesPool demo. The Free function indicates that an instance can be reused, and the Obtain function gets the first unused instance.
The particle effect and the particle effect pool have to be disposed of when they are no longer needed.
Scene2D
Scene2D is a scene graph using a hierarchy of actors. It has a two-way event system and a set of widgets for menus, HUD overlays, dialogs, touchpads, and other Uis.
It makes the creation of games easier and is recommended for beginners. It may seem complex at start because of all the possibilities and classes, but don't be put off by that and try to understand the major principles.
Scene2D has three classes at its core:
The lgScn2DStage class is used to create the stage, i.e. the place where the actors are drawn and can receive input events. It's the root of the hierarchy. It has a camera (lgOrthographicCamera) to define a viewport, a renderer (lgSpriteBatch) to draw the actors and an input processor. It is recommended to have only one stage per application.
The lgScn2DActor class is used to create the actors, i.e. the graphic objects that will take place on the stage. An actor has a position, a rectangular size, an origin, a scale, a rotation angle, and a color.
The lgScn2DGroup class is used to create groups of actors. It allows to do group actions (group movement for example) or group transformations. The stage contains already a group named Root which is the main group.
Stage:
The stage is initialized in the Create event:
In this example, ST is the prefix of the Act and Draw events and the default settings are used: the stage has a viewport equal to the device screen resolution and uses its own SpriteBatch, which will be disposed when the stage is disposed.
It is possible to define another viewport or reuse an existing SpriteBatch with the other Initialize functions.
To add an actor or a group to the stage, use the AddActor function. To remove an actor or a group, call RemoveActor.
To perform the actions attached to actors, call Act in the Render event.
To draw actors, call Draw in the Render event.
Typically, your Render event will look like this:
'Clears the screen
GL.glClear(GL.GL10_COLOR_BUFFER_BIT)
'Runs AI, computes moves and resolves collisions
MyUpdateFunction
'Applies the actions to actors (if you use actions)
Stage.Act
'Draws the actors
Stage.Draw
The stage has to be disposed of when it is no longer needed (all resources used internally by actors will be disposed too).
Actors:
An actor can be created and initialized at any time. It will not be drawn until it is added to the stage. Example:
Dim Elf As lgScn2DActor
Elf.Initialize("Elf")
Elf.Name = "Elf"
Elf.X = 15dip
Elf.Y = 10dip
Elf.Height = 65dip
Elf.Width = 50dip
Stage.AddActor(Elf)
Each actor has an Act and a Draw event, raised by a call to the Act and Draw functions. These functions should be called by their parent, and usually they are called at the stage level (the root group being the parent of all actors). Draw does nothing by default (you have to draw yourself the actor in the event); Act updates and applies the actions attached to the actor (see the Actions section below).
If your actor is an image, you should use the lgScn2DImage class instead of the generic lgScn2DActor class. This way, you won’t have to draw the image in the Draw event. That will be done automatically.
When you want to delete permanently an actor (and not just remove it from the stage), set it to Null.
To see the bounds of an actor, you can use the lgScn2DDebugRenderer class. Once the class is initialized, call the Render function of the renderer in the Render event. You can toggle this rendering for each actor with the DebuggingEnabled property.
Event system:
All groups and actors can receive input events via listeners. These listeners can be added as capture listeners (AddCaptureListener) or as regular listeners (AddListener). In the capture phase, events are propagated from the root down to the deepest actor in the hierarchy, which allows parents to block events before they reach their child actors. After the capture phase, events are sent directly to their target, and if not stopped or cancelled, are propagated in the reverse order of the capture phase: from the targeted actor up to the root. It’s the regular phase.
With the Event parameter, the event handler can limit the propagation of the event:
In the capture phase:
If, in the event handler of a group…
- You do nothing…
The target and all intermediate groups will get the event.
The application will get the event.
- You call Event.Cancel…
The target and all intermediate groups will not see the event.
The application will not see the event.
- You call Event.Stop…
The target and all intermediate groups will not see the event.
The application will get the event.
- You call Event.Handle…
The target and all intermediate groups will get the event.
The application will not see the event.
In the regular phase:
If, in the event handler of the targeted actor…
- You do nothing…
Its parent groups will get the event.
The application will get the event.
- You set Event.Bubbles to false…
Its parent groups will not see the event.
The application will get the event.
- You call Event.Cancel…
Its parent groups will not see the event.
The application will not see the event.
- You call Event.Stop…
Its parent groups will not see the event.
The application will get the event.
- You call Event.Handle…
Its parent groups will get the event.
The application will not see the event.
These two tables suppose that the input processor of the application was declared after the initialization of the stage. If it is declared before, it will intercept all events.
The value of Bubbles is ignored in the capture phase.
In a TouchDown event handler, you must call Event.Handle if you want to fire the TouchDragged and TouchUp events that follow.
Example of event handler:
Sub Elf_Click(Event As lgScn2DInputEvent, X As Float, Y As Float)
Event.Target.Remove
Event.Stop
End Sub
In this example, the Click event is fired when the user touches the screen and lifts up his finger in the same area. The Event parameter is used to remove the actor targeted by the click (the topmost actor under the finger). Then the propagation is stopped, so no other actor or group (including the root group of the stage) will see this event.
List of available listeners:
- lgScn2DInputListener: for keyboard and touch events
- lgScn2DClickListener: for clicks detection
- lgScn2DGestureListener: for gestures detection (pan, zoom, pinch, fling, etc.)
If you want to delegate an event to another actor, look at the Fire and Hit functions.
An actor not visible, not touchable or not on stage cannot receive input events.
Actions:
Each actor may have a list of actions. These actions are added with AddAction and are removed automatically when they are complete. They cover most needs (move, rotate, resize, rescale, show/hide, change alpha, change color...) and can be run at the same time or in sequence. The lgScn2DActions class provides the complete list of actions.
Examples:
Dim Actions As lgScn2DActions
'Will move instantly the actor 10dips to the right
Ogre(0).AddAction(Actions.MoveBy(10dip, 0))
'Will take 5 seconds to move the actor to the bottom left corner
Ogre(1).AddAction(Actions.MoveTo2(0, 0, 5))
'Will hide immediately the actor, then will wait for one second before showing it again
Ogre(2).AddAction(Actions.Sequence2(Actions.Hide, Actions.Delay2(1, Actions.Show)))
Actions are performed when the Act function is called.
Widgets:
A widget is an actor used to build UIs which draws itself and provides a minimum, preferred, and maximum size for dynamic layout. It is similar to the standard views of Basic4Android (Label, EditText, Button, Spinner, etc.).
Most widgets have their appearance defined by a Style (lgScn2DButtonStyle, lgScn2DLabelStyle, lgScn2DWindowStyle, etc.). This style may require images called Drawables, which are variants of the basic image types: lgScn2DNinePatchDrawable for nine-patches, lgScn2DSpriteDrawable for sprites, and lgScn2DTextureRegionDrawable for texture regions. There is a fourth type, based on lgScn2DTextureRegionDrawable: lgScn2DTiledDrawable, which is convenient to repeatedly fill an area instead of stretching the image.
List of widgets (WG indicates a widget group, i.e. a widget that can contain other widgets):
- lgScn2DButton (WG) is an empty Table with a checked state that is toggled each time the Button is clicked. Typically, Images or Labels are added to this widget.
- lgScn2DImage simply displays a Drawable.
- lgScn2DLabel displays a text using a bitmap font and a color. The text may contain newlines (CRLF).
- lgScn2DList is a list box that displays textual items and highlights the selected item. A List does not scroll on its own and is often put in a ScrollPane.
- lgScn2DProgressBar is a horizontal or vertical bar intended to show a progression.
- lgScn2DScrollPane (WG) scrolls a child widget using scrollbars and/or touch dragging. Scrolling is automatically enabled when the widget is larger than the ScrollPane.
- lgScn2DSelectBox is a drop-down list that displays only the selected value when inactive, and shows the list of values that may be selected when activated.
- lgScn2DSlider is a horizontal or vertical indicator that allows a user to set a value.
- lgScn2DSplitPane (WG) contains two widgets and is divided in two either horizontally or vertically. The user may resize the widgets with a draggable splitter.
- lgScn2DTable (WG) is a widget group that sizes and positions its children using a logical table, similar to HTML tables.
- lgScn2DTextButton (WG) is a Button containing a Label.
- lgScn2DTextField is a single line text entry field, with an optional password mode.
- lgScn2DTouchpad is an onscreen joystick that moves in a circular area.
- lgScn2DWindow (WG) is a Table with an area above the contents that displays a title and allows to move the whole. The window can optionally act as a modal dialog, preventing touch events to widgets below.
You can build new widgets by adding widgets to a widget group. Here's an example of “checkbox”:
Sub Globals
…
Dim trdCheckBox(2) As lgScn2DTextureRegionDrawable
Dim imgCheckBox As lgScn2DImage
End Sub
Sub LG_Create
…
'Gets the checked and unchecked drawables from a texture atlas
trdCheckBox(0) = Atlas.CreateRegionDrawable("unchecked")
trdCheckBox(1) = Atlas.CreateRegionDrawable("checked")
'Sets the minimum size of the state drawables
For i = 0 To 1
trdCheckBox(i).MinHeight = 40dip
trdCheckBox(i).MinWidth = 40dip
Next
'Creates an image widget to display one of the state drawables
imgCheckBox.Initialize("")
imgCheckBox.Drawable = trdCheckBox(0) 'Unchecked by default
'Gets the font for the button label
Dim AtlasRegion As lgTextureAtlasRegion = Atlas.FindRegion("arial22")
Font.Initialize4(lGdx.Files.internal("font/arial22.fnt"), AtlasRegion)
Font.Scale(Density)
'Creates a transparent style for the button (no background)
Dim stylButton As lgScn2DButtonStyle
stylButton.Initialize(Null, Null)
'Builds the "checkbox" button (image+label) and adds it to the stage
Dim btnCheckBox As lgScn2DButton
btnCheckBox.Initialize(stylButton, "btnCheckBox")
btnCheckBox.AddActor(imgCheckBox)
btnCheckBox.AddLabel2("Check me", Font, Font.Color.WHITE).SpaceLeft = 10dip
btnCheckBox.Pack 'Adjusts the size of the button to its contents
Stage.AddActor(btnCheckBox)
End Sub
Sub btnCheckBox_Click(CheckedState As Boolean)
'Selects the appropriate drawable for the checked state
If CheckedState Then
imgCheckBox.Drawable = trdCheckBox(1) 'Checked
Else
imgCheckBox.Drawable = trdCheckBox(0) 'Unchecked
End If
End Sub
Tables are intended to be used extensively to layout widgets, as they are easy to use and much more powerful than manually sizing and positioning widgets.
They are made of cells (lgScn2DTableCell) which have their own properties. To create cells in the same row, one after the other, use the AddActor function (with a specified actor/widget) or the AddCell function (to let the cell empty). To start a new row, call NewRow. Once added, the cells cannot be reordered.
I recommend to add a Table as the main child of the root group, and to create everything else inside this Table. This will facilitate the layout of your game screen and will make it more dynamic.
Example (in the Create event):
Stage.Initialize("Stage")
Table.Initialize("RootTable")
Table.FillParent = True
Stage.AddActor(Table)
More information on Tables.
There are two classes intended to be used by widgets: lgScn2DButtonGroup to make “radio” buttons and lgScn2DStack to stack widgets on top of each other.
To rotate (rotateBy, Rotation) or scale (ScaleX, ScaleX, setScale) a widget group and apply this transformation to the children, you have to set the Transform property of the group to True.
Drag & Drop:
The lgScn2DDragAndDrop class can manage drag and drop operations through registered drag sources and drop targets.
Example:
DragAndDrop.Initialize
DragAndDrop.AddSource(mySource, "Src")
DragAndDrop.AddTarget(myTarget, "Tgt")
The source will receive two events:
SrcDragStart: the user started dragging the source. You have to return a “payload” (lgScn2DDragAndDropPayload), i.e. a drag actor that will show where the source is going to be dropped. That can be the source or another actor. You can display two different payloads according to the drop position (valid/invalid). At the end of the drag, the payload will be removed from the stage.
SrcDragStop: the user dropped the source. DropTarget contains the drop target or Null if the drop position is invalid. If you used the source as payload, you can replace it on stage, at its original position.
The target will receive three events:
TgtDrag: the source is dragged over the target. You have to return True or False to indicate whether the source is allowed to be dropped here.
TgtReset: the source is no longer over the target. You can reset any changes you made in the TgtDrag event.
TgtDrop: the source has been dropped on this target.
Box2D
There are many excellent tutorials about Box2D on Internet (those of
iforce2d for example), so I don’t think it’s useful to cover again this topic. The differences with the original version in C++ are not fundamentals.
If you want a version of Box2D with more features (but a lot slower), you may give a try to another library for B4A:
JBox2D.
In libGDX, the main class is lgBox2DWorld.
The lgBox2DBodyEditorLoader class allows to load shapes created with the Aurélien Ribon’s
Physics Body Editor.
The lgBox2DDebugRenderer class is useful to make visible the bodies, joints, bounding boxes, inactive bodies, velocity vectors and/or contact points. Its Render function takes two parameters: the unwrapped object of your lgBox2DWorld instance and the combined matrices of your camera. Example:
Renderer.Render(World.InternalObject, Camera.Combined)
The lgBox2DParticleEmitter class uses ray casting to achieve continuous collision detection against fixtures. If a particle detects collision, it changes its direction before the actual collision would occur. Velocity is 100% reflected. These particles cannot collide to other particles. This is useful to contain an effect between the boundaries of a container. E.g. the flames of a fire in a hallway are not supposed to cross the walls.
Note: The general rule of thumb for Box2D is to use a fixed time step and meters as unit.
The world, the shapes and the debug renderer have to be disposed of when no longer needed.
.....