Friday, 19 September 2014

Running the libgdx demo application on Android

Running the demo application on Android
The Starter Class for the Android application is called MainActivity.java.
The following listing is MainActivity.java from demo-android:
package com.packtpub.libgdx.demo;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android
  .AndroidApplicationConfiguration;
public class MainActivity extends AndroidApplication {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AndroidApplicationConfiguration cfg =
      new AndroidApplicationConfiguration();
    cfg.useGL20 = false;
    initialize(new MyDemo(), cfg);
  }
}
In the preceding code listing, you can see the MainActivity class that inherits
from the AndroidApplication class. This is how Libgdx encapsulates tasks
such as creating a so-called activity that registers handlers to process touch
input, read sensor data, and much more. What is left to do for you is to create
an instance of a class that implements the ApplicationListener interface.
In this case, it is an instance of the MyDemo class. The instances of MyDemo
and AndroidApplicationConfiguration are passed as arguments to the
initialize() method. The configuration is set to not request OpenGL ES 2.0
support on an Android device.
If you are interested in the latest development of Android hardware statistics,
be sure to check out Dashboards on the official Android Developers website:
http://developer.android.com/about/dashboards/index.html#OpenGL.






Additionally, on Android, you will have to take care of a manifest file that defines
a huge list of parameters to configure the application. If you are not yet familiar
with Android's manifest file, you should take some time to read the official
documentation at http://developer.android.com/guide/topics/manifest/
manifest-intro.html.
The following listing is AndroidManifest.xml from demo-android:
<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.packtpub.libgdx.demo"
  android:versionCode="1"
  android:versionName="1.0" >
  <uses-sdk android:minSdkVersion="5"
            android:targetSdkVersion="17" />
<application
  android:icon="@drawable/ic_launcher"
  android:label="@string/app_name" >
<activity
  android:name=".MainActivity"
  android:label="@string/app_name"
  android:screenOrientation="landscape"
  android:configChanges=
    "keyboard|keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The following short (and incomplete) list is meant to give you a quick idea of what
could be defined in the manifest file:
•  minSdkVersion: This is the minimum API Level required for the application
to run. Devices running with lower API Levels will not be able to run this
application; or if left undeclared, an API Level of 1 is assumed, which may
cause your app to crash at runtime when trying to access unavailable APIs.
•  targetSdkVersion: This is the API Level the application targets. This is
used for forward compatibility, where later API Levels may change the
behavior of the API that might break old applications. This specification
does not prevent the application from running on devices with lower API
Levels down to minSdkVersion. If left undeclared, its value is set equal to
minSdkVersion.



Additionally, on Android, you will have to take care of a manifest file that defines
a huge list of parameters to configure the application. If you are not yet familiar
with Android's manifest file, you should take some time to read the official
documentation at http://developer.android.com/guide/topics/manifest/
manifest-intro.html.
The following listing is AndroidManifest.xml from demo-android:
<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.packtpub.libgdx.demo"
  android:versionCode="1"
  android:versionName="1.0" >
  <uses-sdk android:minSdkVersion="5"
            android:targetSdkVersion="17" />
<application
  android:icon="@drawable/ic_launcher"
  android:label="@string/app_name" >
<activity
  android:name=".MainActivity"
  android:label="@string/app_name"
  android:screenOrientation="landscape"
  android:configChanges=
    "keyboard|keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The following short (and incomplete) list is meant to give you a quick idea of what
could be defined in the manifest file:
•  minSdkVersion: This is the minimum API Level required for the application
to run. Devices running with lower API Levels will not be able to run this
application; or if left undeclared, an API Level of 1 is assumed, which may
cause your app to crash at runtime when trying to access unavailable APIs.
•  targetSdkVersion: This is the API Level the application targets. This is
used for forward compatibility, where later API Levels may change the
behavior of the API that might break old applications. This specification
does not prevent the application from running on devices with lower API
Levels down to minSdkVersion. If left undeclared, its value is set equal to
minSdkVersion.

•  icon: This is the application's icon.
•  name: This is the main class of the application (or the main activity). Note that
in terms of Libgdx, this will be the Starter Class for Android.
•  label: This is the application's name shown next to the application icon and
in the title bar.
•  screenOrientation: This defines the display orientation of the application.
The usual values are portrait (tall) and landscape (wide). See the
documentation for more details.
Another crucial part of the manifest file is the correct definition of the permissions
that the application should request when a user wants to install it on a device.


Now, right-click on the demo-android project in Project Explorer in Eclipse and
navigate to Run As | Android Application.
The Android application should now be installed as an application icon and should
be happily running on your Android device. The following photograph is of the
application running on an HTC Desire HD






Starter Classes in libgdx and Running the demo applicationof libgdx on a desktop

Starter Classes
A Starter Class defines the entry point (starting point) of a Libgdx application.
They are specifically written for a certain platform. Usually, these kinds of classes
are very simple and mostly consist of not more than a few lines of code to set
certain parameters that apply to the corresponding platform. Think of them as
a kind of boot-up sequence for each platform. Once booting has finished, the
Libgdx framework hands over control from the Starter Class (for example, the
demo-desktop project) to your shared application code (for example, the demo
project) by calling the different methods from the ApplicationListener interface
that the MyDemo class implements. Remember that the MyDemo class is where the
shared application code begins.


Running the demo application on a desktop
The Starter Class for the desktop application is called Main.java.
The following listing is Main.java from demo-desktop:
package com.packtpub.libgdx.demo;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
public class Main {
  public static void main(String[] args) {
    LwjglApplicationConfiguration cfg =
      new LwjglApplicationConfiguration();
    cfg.title = "demo";
    cfg.useGL20 = false;
    cfg.width = 480;
    cfg.height = 320;
    new LwjglApplication(new MyDemo(), cfg);
  }
}
In the preceding code listing, you see the Main class, a plain Java class without
the need to implement an interface or inherit from another class. Instead, a new
instance of the LwjglApplication class is created. This class provides a couple
of overloaded constructors to choose from. Here, we pass a new instance of the
MyDemo class as the first argument to the constructor. Optionally, an instance of the
LwjglApplicationConfiguration class can be passed as the second argument.
The configuration class allows you to set every parameter that is configurable for
a Libgdx desktop application. In this case, the window title is set to demo and the
window's width and height is set to 480 by 320 pixels.
This is all you need to write and configure a Starter Class for a desktop.

Let us try to run the application now. To do this, right-click on the demo-desktop
project in Project Explorer in Eclipse and then navigate to Run As | Java Application.
Eclipse may ask you to select the Main class when you do this for the first time. Simply
select the Main class and also check that the correct package name (com.packtpub.
libgdx.demo) is displayed next to it.



The desktop application should now be up and running on your computer. If you
are working on Windows, you should see a window that looks as follows

this picture could change in different versions





Libgdx's Application Life-Cycle and Interface

Libgdx's Application Life-Cycle and Interface


The Application Life-Cycle in Libgdx is a well-defined set of distinct system
states. The list of these states is pretty short: create, resize, render, pause,
resume, and dispose.
Libgdx defines an ApplicationListener interface that contains six methods, one
for each system state. The following code listing is a copy that is directly taken from
Libgdx's sources. For the sake of readability, all comments have been stripped.
public interface ApplicationListener {
  public void create ();
  public void resize (int width, int height);
  public void render ();
  public void pause ();
  public void resume ();
  public void dispose ();
}
All you need to do is implement these methods in your main class of the shared
game code project. Libgdx will then call each of these methods at the right time.


The following diagram visualizes the Libgdx's Application Life-Cycle:



Note that a full and dotted line basically has the same meaning in the preceding
figure. They both connect two consecutive states and have a direction of flow
indicated by a little arrowhead on one end of the line. A dotted line additionally
denotes a system event.
When an application starts, it will always begin with create(). This is where the
initialization of the application should happen, such as loading assets into memory
and creating an initial state of the game world. Subsequently, the next state that
follows is resize(). This is the first opportunity for an application to adjust itself
to the available display size (width and height) given in pixels.
Next, Libgdx will handle system events. If no event has occurred in the meanwhile,
it is assumed that the application is (still) running. The next state would be
render(). This is where a game application will mainly do two things:
•  Update the game world model
•  Draw the scene on the screen using the updated game world model

Afterwards, a decision is made upon which the platform type is detected by Libgdx.
On a desktop or in a web browser, the displaying application window can be resized
virtually at any time. Libgdx compares the last and current sizes on every cycle so
that resize() is only called if the display size has changed. This makes sure that
the running application is able to accommodate a changed display size.
Now the cycle starts over by handling (new) system events once again.
Another system event that can occur during runtime is the exit event. When it
occurs, Libgdx will first change to the pause() state, which is a very good place
to save any data that would be lost otherwise after the application has terminated.
Subsequently, Libgdx changes to the dispose() state where an application should
do its final clean-up to free all the resources that it is still using.
This is also almost true for Android, except that pause() is an intermediate state
that is not directly followed by a dispose() state at first. Be aware that this event
may occur anytime during application runtime while the user has pressed the Home
button or if there is an incoming phone call in the meanwhile. In fact, as long as
the Android operating system does not need the occupied memory of the paused
application, its state will not be changed to dispose(). Moreover, it is possible
that a paused application might receive a resume system event, which in this case
would change its state to resume(), and it would eventually arrive at the system
event handler again.

Input Handling in libgdx and File module

Input module
The input module can be accessed either through Gdx.getInput() or by using the
shortcut variable Gdx.input.
In order to receive and handle input properly, you should always implement the
InputProcessor interface and set it as the global handler for input in Libgdx by
calling Gdx.input.setInputProcessor().
Reading the keyboard/touch/mouse input
Query the system for the last x or y coordinate in the screen coordinates where the
screen origin is at the top-left corner by calling either Gdx.input.getX() or Gdx.
input.getY().
•  To find out if the screen is touched either by a finger or by mouse, call Gdx.
input.isTouched()
•  To find out if the mouse button is pressed, call Gdx.input.
isButtonPressed()
•  To find out if the keyboard is pressed, call Gdx.input.isKeyPressed()
Reading the accelerometer
Query the accelerometer for its value on the x axis by calling Gdx.input.
getAccelerometerX(). Replace the X in the method's name with Y or Z to query the
other two axes. Be aware that there will be no accelerometer present on a desktop,
so Libgdx always returns 0.
Starting and canceling vibrator
On Android, you can let the device vibrate by calling Gdx.input.vibrate().
A running vibration can be cancelled by calling Gdx.input.cancelVibrate().

Catching Android soft keys
You might want to catch Android's soft keys to add an extra handling code for them.
If you want to catch the back button, call Gdx.input.setCatchBackKey(true).
If you want to catch the menu button, call Gdx.input.setCatchMenuKey(true).
On a desktop where you have a mouse pointer, you can tell Libgdx to catch
it so that you get a permanent mouse input without having the mouse ever
leave the application window. To catch the mouse cursor, call Gdx.input.
setCursorCatched(true).
The files module
The files module can be accessed either through Gdx.getFiles() or by using the
shortcut variable Gdx.files.
Getting an internal file handle
You can get a file handle for an internal file by calling Gdx.files.internal().
An internal file is relative to the assets folder on the Android and WebGL
platforms. On a desktop, it is relative to the root folder of the application.
Getting an external file handle
You can get a file handle for an external file by calling Gdx.files.external().
An external file is relative to the SD card on the Android platform. On a
desktop, it is relative to the user's home folder. Note that this is not available
for WebGL applications.
The network module

The network module can be accessed either through Gdx.getNet() or by using the 
shortcut variable Gdx.net.
HTTP GET and HTTP POST
You can make HTTP GET and POST requests by calling either Gdx.net.httpGet()
or Gdx.net.httpPost().
Cross-platform Development – Build Once, Deploy Anywhere
[ 58 ]
Client/server sockets
You can create client/server sockets by calling either Gdx.net.newClientSocket()
or Gdx.net.newServerSocket().
Opening a URI in a web browser
To open a Uniform Resource Identifier (URI) in the default web browser, call Gdx.
net.openURI(URI).



Persisting data in libgdx

Persisting data
If you want to persist your data, you should use the Preferences class. It is merely
a dictionary or a hash map data type which stores multiple key-value pairs in a
file. Libgdx will create a new preferences file on the fly if it does not exist yet. You
can have several preference files using unique names in order to split up data into
categories. To get access to a preference file, you need to request a Preferences
instance by its filename as follows:
Preferences prefs = Gdx.app.getPreferences("settings.prefs");
To write a (new) value, you have to choose a key under which the value should be
stored. If this key already exists in a preferences file, it will be overwritten. Do not
forget to call flush() afterwards to persist the data, or else all the changes will
be lost.
prefs.putInteger("sound_volume", 100); // volume @ 100%
prefs.flush();

Persisting data needs a lot more time than just modifying values in 
memory (without flushing). Therefore, it is always better to modify as 

many values as possible before a final flush() method is executed

To read back a certain value from a preferences file, you need to know the
corresponding key. If this key does not exist, it will be set to the default value.
You can optionally pass your own default value as the second argument
(for example, in the following listing, 50 is for the default sound volume):

int soundVolume = prefs.getInteger("sound_volume", 50);

Querying the Android API Level

On Android, you can query the Android API Level, which allows you to handle
things differently for certain versions of the Android OS. Use the following listing
to find out the version:
Gdx.app.getVersion();

On platforms other than Android, the version returned is always 0.


Querying memory usage
You can query the system to find out its current memory footprint of your
application. This may help you find excessive memory allocations that could lead to
application crashes. The following functions return the amount of memory (in bytes)
that is in use by the corresponding heap:
long memUsageJavaHeap = Gdx.app.getJavaHeap();
long memUsageNativeHeap = Gdx.app.getNativeHeap();
Graphics module
The graphics module can be accessed either through Gdx.getGraphics() or by
using the shortcut variable Gdx.graphics.
Querying delta time
Query Libgdx for the time span between the current and the last frame in seconds by
calling Gdx.graphics.getDeltaTime().
Querying display size
Query the device's display size returned in pixels by calling Gdx.graphics.
getWidth() and Gdx.graphics.getHeight().
Querying the FPS (frames per second) counter
Query a built-in frame counter provided by Libgdx to find the average number of
frames per second by calling Gdx.graphics.getFramesPerSecond().
Audio module
The audio module can be accessed either through Gdx.getAudio() or by using the
shortcut variable Gdx.audio.
Sound playback
To load sounds for playback, call Gdx.audio.newSound().
The supported file formats are WAV, MP3, and OGG.
There is an upper limit of 1 MB for decoded audio data. Consider the sounds to be
short effects like bullets or explosions so that the size limitation is not really an issue.

Music streaming
To stream music for playback, call Gdx.audio.newMusic().
The supported file formats are WAV, MP3, and OGG.





Cross-platform Development – Build Once, Deploy Anywhere

Cross-platform Development – Build Once, Deploy Anywhere

you will learn more about the generated Eclipse projects and how
they work together. Also, you will learn more about the following components of
the Libgdx framework:
•  Backends
•  Modules
•  Application Life-Cycle and Interface
•  Starter Classes
At the end of this chapter, you will take a closer look at the demo application and
inspect the generated code of the Main class in great detail. You will learn how to
set breakpoints, run the application in debug mode, and speed up your overall
productivity with the awesome JVM Code Hot Swapping feature. The discussion
on the demo application ends with some simple and fun modifications to the code

accompanied by a demonstration of the JVM Code Hot Swapping feature

The demo application – how the projects
work together
 Introduction to Libgdx and Project Setup, we successfully created our demo
application, but we did not look at how all the Eclipse projects work together. Take
a look at the following diagram to understand and familiarize yourself with the
configuration pattern that all of your Libgdx applications will have in common:

What you see here is a compact view of four projects. The demo project to the very
left contains the shared code that is referenced (that is, added to the build path) by
all the other platform-specific projects. The main class of the demo application is
MyDemo.java. However, looking at it from a more technical view, the main class
where an application gets started by the operating system, which will be referred to
as Starter Classes from now on. Notice that Libgdx uses the term "Starter Class" to
distinguish between these two types of main classes in order to avoid confusion.
We will cover everything related to the topic of Starter Classes
in a moment.
While taking a closer look at all these directories in the preceding screenshot, you
may have spotted that there are two assets folders: one in the demo-desktop project
and another one in demo-android. This brings us to the question, where should you
put all the application's assets? The demo-android project plays a special role in this
case. In the preceding screenshot, you see a subfolder called data, which contains an
image named libgdx.png, and it also appears in the demo-desktop project in the
same place.

Just remember to always put all of your assets into the assets folder 
under the demo-android project. The reason behind this is that the 
Android build process requires direct access to the application's 
assets folder. During its build process, a Java source file, R.java, 
will automatically be generated under the gen folder. It contains special 
information for Android about the available assets. It would be the usual 
way to access assets through Java code if you were explicitly writing an 
Android application. However, in Libgdx, you will want to stay platform-independent as much as possible and access any resource such as assets 
only through methods provided by Libgdx. 

You may wonder how the other platform-specific projects will be able to access the 
very same assets without having to maintain several copies per project. Needless to 
say that this would require you to keep all copies manually synchronized each time 
the assets change.
Luckily, this problem has already been taken care of by the generator as follows:
The demo-desktop project uses a linked resource, a feature by Eclipse, to add 
existing files or folders to other places in a workspace. You can check this out by 
right-clicking on the demo-desktop project then navigating to Properties |  
Resource | Linked Resources and clicking on the Linked Resources tab.
The demo-html project requires another approach since Google Web Toolkit (GWT) 
has a different build process compared to the other projects. There is a special 
file GwtDefinition.gwt.xml that allows you to set the asset path by setting the 
configuration property gdx.assetpath, to the assets folder of the Android project. 
Notice that it is good practice to use relative paths such as ../demo-android/
assets so that the reference does not get broken in case the workspace is moved 
from its original location. Take this advice as a precaution to protect you and maybe 
your fellow developers too from wasting precious time on something that can be 
easily avoided by using the right setup right from the beginning.
The following is the code listing for GwtDefinition.gwt.xml from demo-html:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit
  trunk//EN" "http://google-web-toolkit.googlecode.com/svn/trunk/
    distro-source/core/src/gwt-module.dtd">
<module>
<inherits name='com.badlogic.gdx.backends.gdx_backends_gwt' />
<inherits name='MyDemo' />
<entry-point  class='com.packtpub.libgdx.demo.client.GwtLauncher' />
  <set-configuration-property name="gdx.assetpath"
    value="../demo-android/assets" />
</module>


Backends
Libgdx makes use of several other libraries to interface the specifics of each platform 
in order to provide cross-platform support for your applications. Generally, a 
backend is what enables Libgdx to access the corresponding platform functionalities 
when one of the abstracted (platform-independent) Libgdx methods is called. For 
example, drawing an image to the upper-left corner of the screen, playing a sound 
file at a volume of 80 percent, or reading and writing from/to a file.
Libgdx currently provides the following three backends:
•  LWJGL (Lightweight Java Game Library)
•  Android
•  JavaScript/WebGL

LWJGL (Lightweight Java Game Library)
LWJGL (Lightweight Java Game Library) is an open source Java library originally 
started by Caspian Rychlik-Prince to ease game development in terms of accessing 
the hardware resources on desktop systems. In Libgdx, it is used for the desktop 
backend to support all the major desktop operating systems, such as Windows, 
Linux, and Mac OS X.
For more details, check out the official LWJGL website at http://www.lwjgl.org/.


Android
Google frequently releases and updates their official Android SDK. This represents 
the foundation for Libgdx to support Android in the form of a backend.
There is an API Guide available which explains everything the Android SDK has to 
offer for Android developers. You can find it at http://developer.android.com/
guide/components/index.html.

WebGL

WebGL support is one of the latest additions to the Libgdx framework. This backend 
uses the GWT to translate Java code into JavaScript and SoundManager2 (SM2), 
among others, to add a combined support for HTML5, WebGL, and audio  
playback. Note that this backend requires a WebGL-capable web browser  
to run the application.
You might want to check out the official website of GWT:  
https://developers.google.com/web-toolkit/.
You might want to check out the official website of SM2:  
http://www.schillmania.com/projects/soundmanager2/.
You might want to check out the official website of WebGL:  
http://www.khronos.org/webgl/.
There is also a list of unresolved issues you might want to check out at  
https://github.com/libgdx/libgdx/blob/master/backends/gdx-backends-gwt/issues.txt



Modules
Libgdx provides six core modules that allow you to access the various parts of the 
system your application will run on. What makes these modules so great for you 
as a developer is that they provide you with a single Application Programming 
Interface (API) to achieve the same effect on more than just one platform. This is 
extremely powerful because you can now focus on your own application and you 
do not have to bother with the specialties that each platform inevitably brings, 
including the nasty little bugs that may require tricky workarounds. This is all going 
to be transparently handled in a straightforward API which is categorized into logic 
modules and is globally available anywhere in your code, since every module is 
accessible as a static field in the Gdx class.
Naturally, Libgdx does always allow you to create multiple code paths for  
per-platform decisions. For example, you could conditionally increase the level  
of detail in a game when run on the desktop platform, since desktops usually  
have a lot more computing power than mobile devices.
The application module
The application module can be accessed through Gdx.app. It gives you access to the 
logging facility, a method to shutdown gracefully, persist data, query the Android 
API version, query the platform type, and query the memory usage.
Logging
Libgdx employs its own logging facility. You can choose a log level to filter what 
should be printed to the platform's console. The default log level is LOG_INFO. You 
can use a settings file and/or change the log level dynamically at runtime using the 
following code line:
Gdx.app.setLogLevel(Application.LOG_DEBUG);
The available log levels are:
•  LOG_NONE: This prints no logs. The logging is completely disabled.
•  LOG_ERROR: This prints error logs only.
•  LOG_INFO: This prints error and info logs.
•  LOG_DEBUG: This prints error, info, and debug logs.



To write an info, debug, or an error log to the console, use the following listings:
Gdx.app.log("MyDemoTag", "This is an info log.");
Gdx.app.debug("MyDemoTag", "This is a debug log.");
Gdx.app.error("MyDemoTag", "This is an error log.");
Shutting down gracefully
You can tell Libgdx to shutdown the running application. The framework will then 
stop the execution in the correct order as soon as possible and completely de-allocate 
any memory that is still in use, freeing both Java and the native heap. Use the 
following listing to initiate a graceful shutdown of your application:
Gdx.app.exit();

You should always do a graceful shutdown when you want to 
terminate your application. Otherwise, you will risk creating 
memory leaks, which is a really bad thing. On mobile devices, 
memory leaks will probably have the biggest negative impact 
due to their limited resources.

Game project – Canyon Bunny

Game project – Canyon Bunny
To make this guide both easy and fun to read, it makes perfect sense to show how
to plan and develop a whole game project throughout this book. As we now know,
planning should be the first step to take on the journey of any new game project.
So, let us begin with the outline:
Name or Working Title: Canyon Bunny
Genre: 2D Side-Scrolling Jump and Run

List of actors:
       •  Player character (can jump and move forward; controlled   by player)
       •  Rocks, serving as platforms for the player character and items
       •  Canyons in the background (level decoration)
       •  Clouds in the sky (level decoration)
       •  Water at the bottom of the level (deadly for player character)
       •  Collectible items for the player: gold coins, feather power-up
Next, it is always helpful to write down some supporting text to further describe the
overall behavior of the game and how features should be implemented.


Description of the game

The game world is presented in 2D side view to the player. The view is scrolling
horizontally to the right when the player character moves forward. The background
shows distant canyons and clouds in the sky. The bottom of the level is filled with
water and will instantly kill the player character if both get into contact with
each other.
The player character will move on and jump over to random rocks, sticking
out of the water. The width and height will be different to make the game more
challenging. The player is only in control of a jump button, which will keep
the automatically forward-moving player character from falling down into
the deadly water.
The level will be randomly populated with collectible items consisting of gold coins
and feather power-ups. Collecting the gold coins will increase the player's high score.
The feather power-up grants the player character the ability to fly for a limited time
and can be used by repeatedly pressing the jump button. The player's goal is to beat
the last high score.
Since a picture is worth a thousand words, creating a sketch based on our outline
can help us even more to get a better idea of the resulting game. Moreover, changing
a sketch is usually a lot easier than having to change (complex) game code. So you
really want to keep it very simple like just grabbing your pen and paper and starting
to draw. If you feel lucky or have some time to spend, you can do something more
elaborate, of course.

Here is a sketch for Canyon Bunny:


The previous sketch has been created entirely by using vector graphics.

Using vector graphics in favor of raster graphics for your sketches can be an advantage
as they are infinitely scalable to any size without losing image quality. However,
the final graphics used in games are almost, always, rasterized graphics, simply
because vector graphics are costly to render in real time. So, the common approach
is to create vector graphics and later on export them choosing an appropriate
rasterized graphics file format, such as .png (Portable Network Graphics) for
lossless compression with alpha channel support, or .jpg (JPEG) for lossy
but high compression without alpha channel support.
For more details, check out the following Wikipedia articles:
•  For information on raster graphics go to
http://en.wikipedia.org/wiki/Raster_graphics
•  For information on vector graphics go to
http://en.wikipedia.org/wiki/Vector_graphics
•  For information on PNG file format go to
http://en.wikipedia.org/wiki/.png
•  For information on JPEG file format go to
http://en.wikipedia.org/wiki/.jpg
There is a free and open source tool called Inkscape. It allows you to easily create
your own drawings as vector graphics, and is available for Windows, Linux, and

Mac OS X. Check out the project's website at http://inkscape.org/.

Kicking your game to life

Let us take a moment to discuss what a game basically consists of. From a very
high level point of view, a game can be split up into two parts: game assets and
game logic.

Game assets include everything that is going to be used as a kind of working
material in your game, such as images, sound effects, background music,
and level data.

Game logic is responsible for keeping track of the current game state and to only
allow a defined set of state transitions. These states will change a lot over time due
to the events triggered either by the player or by the game logic itself. For example,
when a player presses a button, picks up an item, or an enemy hits the player, the
game logic will decide for the appropriate action to be taken. All this is better known
as game play. It constrains the ways of action in which a player can interact with the
game world, and also how the game world would react to the player's actions.







The very first step is to initialize the game, that is, loading assets into memory,
creating the initial state of the game world, and registering with a couple of
subsystems such as input handlers for keyboard, mouse and touch input,
audio for playback and recording, sensors, and network communication.
When everything is up and running, the game logic is ready to take over and will
loop for the rest of the time until the game ends and will then be terminated. This
kind of looping is also referred to as the game loop. Inside the game loop, the game
logic accumulates all (new) data it is interested in and updates the game world
model accordingly.

It is very important to consider the speed at which updates will occur in the game
world. Currently, the game would just run at the maximum speed of the available
hardware. In most cases this is not a desirable effect because it makes your game
dependent on the processing power and the complexity of the scene to be rendered,
which will vary from computer to computer. This implies that your game world
will also progress at different speeds on different computers with an almost always
negative impact on the game play.

The key to tackle this issue is to use delta times to calculate the fractional progress
of the game world. Now every update to the game world will occur in relation to
real time that has passed since the last frame was rendered. You will see how this
actually works with Libgdx in later examples.

What you have just read was an overview of the basic concept for creating games.
Yes, it is that simple! Frankly speaking, there is a lot more to learn before your
application becomes a real game. There are lots of topics and concepts waiting to
be discovered in this book. For instance, you will need to understand how to use
and manage different images in an efficient manner. Efficiency becomes even more
important if you plan to target mobile devices such as Android smartphones, where
available resources are constantly scarce.



Key to success lies in planning
Great! Now you have a basic understanding of what a game is and may need. It
appears to be a good idea to dedicate some additional time to think about your
first game project and create a plan for it. In general, planning your game projects
is what you should always do in the first place before any actual work is done. For
novice game developers it might be very tempting to skip this planning phase,
which admittedly is a lot more fun in the beginning, but this approach is very likely
to fall short in the long run. You will need some sort of outline of what you want to
achieve. It does not have to be a very long and detailed description.


A simple and brief feature list of your design goals will do just fine for this purpose.
The reason behind this is that you will make yourself aware of each single feature
that is part of your game. In addition, this list will also serve you as a great tool to
measure and compare your progress in the game during the development phase.
Please bear in mind that game development is a very dynamic and iterative process.
Although you should try to adhere to your list of design goals for most of the time,
there should always be room to adapt to shifting requirements. Just keep in mind
that adhering to the list will make sure that you are going to push development in
the right direction. Conversely, it will let you focus on the important parts first,
while also protecting you from running out of time and taking too many detours
that prevent you from reaching the finish line due to unclear goals.

Tuesday, 16 September 2014

Introduction to Libgdx and Project Setup



FOR Video tutorial of libgdx AND BOX2D


This blog will take you on an exciting tour to show and teach you about game
development using the open source Libgdx framework. Actually, you have chosen
just the right time to read about game development as the game industry is in a
remarkable state of change.



Creating a libgdx project

Libgdx comes with a file called gdx-setup.jar which is an executable UI and command line tool. You can simply execute the JAR file which will open the setup UI.
To execute the JAR file at the command line:
java -jar gdx-setup.jar

Download gdx-setup.jar

Specify your application name, your Java package name, the name of your main class, the output directory, and the path to your android sdk. Next, you can select what platforms you want to support. Note: once chosen, you'll have to add new platforms manually!. Finally, you can select extensions to be included in your app. Some may not work on all platforms, for which you'll get a warning. When you've set everything, click "Generate". Now you are ready to import the project into your IDE, run, debug and package it!
  • Eclipse





























Importing Your Project

Go to File -> Import -> Gradle -> Gradle Project, click Browse and navigate to the root folder of your project, then click Build Model. After a while, you'll see a root project and subprojects (android, core, desktop, html, ios). Select all the projects and click Finish. Note that this process can take a minute or two the first time you do it, as Gradle and some dependencies will be downloaded in the background.

Running Your Project

  • Desktop: Right click the desktop project, Run As -> Java Application. Select the desktop starter class (e.g. DesktopLauncher.java).
  • Android: make sure you have a device connected and that it shows up in DDMS (see Android Developer Guide). Right click your Android project, Run As -> Android Application.
  • iOS RoboVM: Right click the robovm project, Run As -> iOS Device App to run on a connected device, or Run As -> iOS Simulator App to run on the iOS simulator. If you run on a device, you need to provision it to be able to deploy to it!
  • HTML5: Right click the html project, Run As -> External Tools Configuration. Create a new configuration by double clicking the Programentry in the left sidebar. Give the configuration a name, e.g. GWT SuperDev. Set the location field to the gradlew.bat (Windows) or gradlew (Linux, Mac) file. Set the working directory to the root folder of your project. Specifyhtml:superDev as the Argument. Press 'Apply', then 'Run'. Wait until you see the message The code server is ready. in the console view, then open the URL http://localhost:8080/html. You can leave the server running. If you change code or assets, simply click the SuperDev Refresh button in the browser. This will recompile your app and reload the site.
Once this bug in the Gradle tooling API is fixed, we can simplify running the HTML5 by using the Gradle integration. At the moment, the Gradle process will run forever even if canceled.

Introduction to Libgdx
Libgdx is an open source, cross-platform development framework, which is designed mainly, but not exclusively, to create games using the Java programming language. Besides Java, Libgdx also makes heavy use of the C programming language for  performance-critical tasks, to incorporate other C-based libraries and to enable  cross-platform capabilities. Moreover, the framework abstracts the complex  nature of all its supported target platforms by combining them into one common Application Programming Interface (API). One of the highlights of Libgdx is the ability to run and debug your code on the desktop as a native application. This enables you to use very comfortable functions of the Java Virtual Machine (JVM)such as Code Hot Swapping, which in turn lets you immediately see the effect of your changed code at runtime. Therefore, it will significantly reduce your time to iterate through different ideas or even to find and fix nasty bugs more quickly.
Another critical point is to understand that Libgdx is a framework and not a game engine that usually comes with lots of tools, such as a full-blown level editor and a completely predefined workflow. This might sound like a disadvantage at first but actually it turns out to be an advantage that enables you to freely define your own workflow for each project. For example, Libgdx allows you to go low-level so you could add your own OpenGL calls if that really became necessary at some point. However, most of the time it should be sufficient enough to stay high-level and  use the already built-in functionalities of Libgdx to realize your ideas.

Goals and Features

Libgdx is a Java game development framework that provides a unified API that works across all supported platforms.
The framework provides an environment for rapid prototyping and fast iterations. Instead of deploying to Android/iOS/Javascript after each code change, you can run and debug your game on the desktop, natively. Desktop JVM features like code hotswapping reduce your iteration times considerably.
Libgdx tries not be the "end all, be all" solution. It does not force a specific design on you. Pick and choose from the features below.

Cross-Platform

A single API to target:
  • Windows
  • Linux
  • Mac OS X
  • Android (2.2+)
  • BlackBerry
  • iOS
  • Java Applet (requires JVM to be installed)
  • Javascript/WebGL (Chrome, Safari, Opera, Firefox, IE via Google Chrome Frame)

Graphics

Utilities

Tools

3rd Party Support

Libgdx can be integrated with many 3rd party tools. We love:
  • Spine - 2D Skeletal Animation
  • Nextpeer - Mobile multiplayer made easy
  • Saikoa - makers of ProGuard and DexGuard

Audio

Input Handling

Math & Physics

File I/O & Storage