Tutorial #4 Moving a shape and shooting a bullet (simple non box2D example)

Welcome back!  This is tutorial #4.  I’m going to  demonstrate how to draw and move some shapes.  In this tutorial, we will draw a shape that represents a tank and give it the ability to “shoot” a bullet in the direction the shape is facing.   The class we will be creating should be added to the framework we created in Tutorial #3 for managing our tutorial classes.

So let’s begin…..

First we want to create a new class and have it extend from Tutorial.  If you do not have the Tutorial class, head back to my tutorial #3 and create it from there.

In our class we want to create some member variables for holding information about the shapes we are going to draw.

First we need to specify the size of our objects.  Create three constants to store the object size,  bullet size and movement speed (in pixels).  The tank size will be used to set the size of our tank and the bullet size is used to set the size of a bullet.  I created the following:

	private static final int TANK_SIZE = 32;
	private static final int BULLET_SIZE = 5;
	private static final int MOVEMENT_SPEED = 50;

Since all our objects are going to be square in shape, I only need to set one value for the width and height.  Thus our tank will be 32 pixels square, bullet will be 5 pixels square and our objects will move at 50 pixels per second (we’ll get to that in a bit).

Next, we need to create a SpriteBatch object to be used for drawing everything.

	// Used for drawing our items
	private SpriteBatch spriteBatch;

Then we need to to specify 4 Vector2 objects.  Two objects that represent the position of our tank and of our bullet when fired.  Two objects that represent the direction of travel for our tank and bullet.

	// Tank position
	private Vector2 tank_pos;
	// bullet position
	private Vector2 bullet_pos;

	// Tank direction
	private Vector2 objectDirection;
	// Bullet direction
	private Vector2 bulletDirection;

And finally we need a few “helper” variables.  We create a Pixmap object to draw our shapes and we will store the current screen width and height to make our life easier.

	private Pixmap pixmap;
	int screenWidth, screenHeight;

With that set, we are ready to write our methods.  We will need three (3) methods.  We will override the create method and initialize our objects.  We will override the render method to do the drawing of our objects.  We will create a private update method to update the position of our objects.  So let’s start with the create method.

I won’t get into detail as this method only initializes our member variables.  This method should similar to

	@Override
	public void create() {
		spriteBatch = new SpriteBatch();
		screenWidth = Gdx.graphics.getWidth();
		screenHeight = Gdx.graphics.getHeight();
		tank_pos = new Vector2(screenWidth / 2 - TANK_SIZE / 2,
				screenHeight / 2 - TANK_SIZE / 2);
		bullet_pos = null;
		objectDirection = new Vector2(1, 0); // Pointing right
		bulletDirection = new Vector2(1, 0);

		pixmap = new Pixmap(32, 32, Pixmap.Format.RGB565);
	}

The first line creates a new SpriteBatch object.  We do it here obviously cause we only want to create it once.
The next two lines stores the screen width and height.
The next line centers our tank in the window.  The tank itself has to be centered as the bottom left corner is the focus point.
Then we set the bullet position to null because if it’s null, we won’t draw it.
Next, we set the tank to face to the right and guarantee that if the fire button is pressed, the bullet will fly to the right as well.
And finally, we create a new Pixmap to use for drawing our shapes.

Now, we need to override the render method so we can add out code to update and draw our objects.  This method is called every frame.  Unfortunately, there is no update method to override so that’s the reason we created one.  In our render method, we want to call our update method to set the position of our objects.  Then, we want to clear the screen, draw our bullet and then our tank.   Your method should look similar to

	@Override
	public void render() {
		update();
		GL10 gl = Gdx.graphics.getGL10();
		gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
		gl.glClearColor(1, 1, 1, 0);
		gl.glClear(GL.GL_COLOR_BUFFER_BIT);

		spriteBatch.begin();
		if (bullet_pos != null) {
			// Draw bullet
			pixmap.drawRectangle(0, 0, BULLET_SIZE, BULLET_SIZE);
			spriteBatch.setColor(Color.BLUE);
			spriteBatch.draw(new Texture(pixmap), bullet_pos.x, bullet_pos.y,
					BULLET_SIZE, BULLET_SIZE);
		}
		// Draw object
		pixmap.drawRectangle(0, 0, TANK_SIZE, TANK_SIZE);
		spriteBatch.setColor(Color.GREEN);
		spriteBatch.draw(new Texture(pixmap), tank_pos.x, tank_pos.y,
				TANK_SIZE, TANK_SIZE);
		spriteBatch.end();
	}

First, we call our update function.  We’ll write that in a bit.   After that, we clear our screen and then tell the spriteBatch object to begin “recording” our draw calls.
We then check to see if a bullet has been created (not null).  If so, we use the pixmap object to create a rectangle of bullet size in memory.  Then we set our draw color to be blue and we use the spriteBatch object place in it’s buffer that we want to draw this rectangle at the current bullet position with a size of bullet size.  We need to set the size because this pixmap is also used for drawing our tank and if we didn’t specify a size, the bullet would be the size of the pixmap which is 32×32.  A pretty big bullet.
After that, we draw our tank using the same method as drawing the bullet except we use a different color.
Finally, we basically tell the spriteBatch object to stop recording and perform all the draw calls all at once.

Finally, we need to create our update method.  In this method, we need to get what keystrokes were pressed, creaing our bullets and moving our tank.

First, we create a new Vector2 object to store temporary store a direction.
Next, we create a variable (you can name it delta) for storing the “delta time.”  multiplied by the overall movement speed.

Delta time is the time that has passed since the beginning of the last frame in milliseconds.  

This is used to control how often our objects get updated.  We multiple this value by the movement speed because all our objects will move at the same rate.  If they had their own individual speeds, then we wouldn’t do the multiplication here but when we’re setting our object position.  By the way, if we didn’t use this “delta” variable,  then our objects would move too fast.  For example, if we moved our tank at a rate of 50 pixels.  It would fly off the screen cause this function gets called hundreds of times a second and holding down a button can easily cause your tank to move 500+ pixels in any give direction instantly.  But using this variable, we can control things a bit.  We can then say our tank moves at a rate of 50 pixels per second or basically, if we held down a key, our tank would take 1 second to move 50 pixels.  Big difference huh.

Back to our update function.  We then check to see if one or all of the directional pads are pressed.  if the right or left is pressed, then the temporary direction variable’s x value is set to 1 or -1 (respectively) multiplied by our delta variable.
We then check to see if our temporary direction variable has had either of it’s x or y values set and if so, we add this value to the tank’s position.  This will move the tank by that direction amount.   If the tanks’ position was 1,1 and the direction was 1,1 then the tank’s position will be 2,2.
There is then a check to make sure our tank doesn’t go off the screen.  We make sure the x value is greater than 0 and less than the screen width minus the tank size.  Similar for the y value.  It has to be  greater than 0 and less than the screen height minus the tank size.  Again, remember the tank’s focal point is in the bottom left corner so  we need to subtract the tank’s width so that the right side or top side does not go off the screen.

After we position the tank if necessary, we check to see if the “F” key (for fire) has been pressed.  If so, we create a new bullet with an origin in the center of the tank with it’s direction equal to that of the tank.

Finally, we check to see if a bullet has been created and if so we move it in it’s intended direction.  If the bullet goes off screen, we remove it by setting it to null.  That’s it.  The code looks like

	private void update() {
		Vector2 direction = new Vector2(0, 0);
		float delta = Gdx.graphics.getDeltaTime() * MOVEMENT_SPEED;
		if (Gdx.input.isKeyPressed(Keys.DPAD_RIGHT)) {
			direction.x = 1 * delta;
		}
		if (Gdx.input.isKeyPressed(Keys.DPAD_LEFT)) {
			direction.x = -1 * delta;
		}
		if (Gdx.input.isKeyPressed(Keys.DPAD_UP)) {
			direction.y = 1 * delta;
		}
		if (Gdx.input.isKeyPressed(Keys.DPAD_DOWN)) {
			direction.y = -1 * delta;
		}
		if (direction.x != 0 || direction.y != 0) {
			tank_pos.add(direction);
			if (tank_pos.x < 0)
				tank_pos.x = 0;
			if (tank_pos.x > this.screenWidth - TANK_SIZE)
				tank_pos.x = this.screenWidth - TANK_SIZE;
			if (tank_pos.y < 0)
				tank_pos.y = 0;
			if (tank_pos.y > this.screenHeight - TANK_SIZE)
				tank_pos.y = this.screenHeight - TANK_SIZE;
			objectDirection.set(direction);
		}

		if (Gdx.input.isKeyPressed(Keys.F)) {
			bullet_pos = new Vector2(tank_pos.cpy().add(
					TANK_SIZE / 2 - BULLET_SIZE / 2,
					TANK_SIZE / 2 - BULLET_SIZE / 2));
			bulletDirection.set(objectDirection);
		}

		if (bullet_pos != null) {
			bullet_pos.add(bulletDirection);
			if (bullet_pos.x < 0 || bullet_pos.x > this.screenWidth
					|| bullet_pos.y < 0 || bullet_pos.y > this.screenHeight) {
				bullet_pos = null;

			}
		}
	}

If you run your Tutorial application and run the ShapeMovementTutorial, you should see the tank in green.  Use the arrow keys on your keyboard or directional keys on your phone to move the tank and click “F” to fire a blue bullet.  Cool.

Figure 4-1

As always, the source for this tutorial is here.  No libgdx jars files are included.

 

LibGdx Tutorial #3 Setting up a testing class for our tutorials

Hi, welcome to the third entry in my LibGdx tutorials.  What we are going to do here is provide an interface for running all our sample programs.

 

First, we must create a new java project.

Next, create a new abstract class and have it implement ApplicationListener.  All of our test classes will extend from this abstract class.  We could have all of our classes implement ApplicationListener directly but using our own abstract class makes management easier.

Next, we need to create a helper class that will store the names to all of our tutorials.  For each tutorial that we create, we’ll add a reference to it here.  This class will also be responsible for returning the names of all of our tutorials.    Thus, create a new class.  I called my class Tutorials.

Inside this class, I create a array variable to hold the reference to all of our test classes.

	public static final Class[] tutorials = { };

 

This array takes a comma delimited list of class names.  For each test class we create, we will add it to this array.  The first class we will add will be our HelloLibGDX class so starting off, we should have

	public static final Class[] tutorials = { HelloLibGDX.class };

 

Next, we need two static functions.  One to return the list of tutorial names and another to new instance of a particular tutorial.

The first class loops through the array “tutorials” and builds a list of strings based off the simple name.  The list is then sorted and returned as an array of strings.

	public static String[] getTutorialNames() {
		List<String> names = new ArrayList<String>();
		for (Class clazz : tutorials)
			names.add(clazz.getSimpleName());
		Collections.sort(names);
		return names.toArray(new String[names.size()]);
	}

 

The next function takes two (2) parameters.  One for the package name and one for the tutorial name.

	public static Tutorial newTutorial(String packageName, String tutorialName) {
		try {
			Class clazz = Class.forName(packageName + "." + tutorialName);
			return (Tutorial) clazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

 

Now, create a new package to hold all the tutorial classes.  Then copy the HelloLibGDX class into this package and change it to extend from Tutorial.

Like before, create the libs folder and copy the LibGdx jars needed for a desktop application and link the jars in the project properties.

After that, let’s create our desktop starter class.  We do the desktop before the android starter because it’s faster to test and debug via the desktop than have to go through the emulator.  So on that note, let’s create the desktop starter class.

 

Create a new class and called it “desktopStarter” or whatever you want.  Create the standard main function and inside, we want to create a new JFrame.

Set the close operation to be JFrame.EXIT_ON_CLOSE so that when the window closes, our application is terminated.

Set the content pane to be a new instance of TutorialPanel()  which we will build in a shortly.

Then set the size and set the visibility to true to display our frame.

You’re main method should look similar to

	public static void main(String[] args) {
		JFrame frame = new JFrame("Karim Amin Tutorial Launcher");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(new TutorialPanel());
		frame.setSize(400, 600);
		frame.setVisible(true);
	}

 

Still within this class, create a nested class and have it extend from JPanel.  This panel will hold the list of tutorial names and a button to load the selected tutorial.

So in the constructor of this nested class, create a new JButton object for the user to click to run the selected tutorial.  Create a new JList object and pass it the list of tutorial names returned from Tutorials.getTutorialNames().   Add a mouse click listener so that when the user double clicks the mouse, it executes a button click.  Then add a button action listener  so that when the button is clicked, we retrieve the name of the tutorial from the list,  create a new instance of the selected tutorial and execute it. Then add both the list and button objects to the panel.

public class DesktopTutorialApp {
	public static void main(String[] args) {
		JFrame frame = new JFrame("Karim Amin Tutorial Launcher");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(new TutorialPanel());
		frame.setSize(400, 600);
		frame.setVisible(true);
	}

	static class TutorialPanel extends JPanel {
		private static final long serialVersionUID = 1L;

		public TutorialPanel() {
			setLayout(new BorderLayout());

			final JButton button = new JButton("Execute Tutorial");
			final JList list = new JList(Tutorials.getTutorialNames());

			list.addMouseListener(new MouseAdapter() {

				public void mouseClicked(MouseEvent event) {
					// Only if we double clicked
					if (event.getClickCount() == 2)
						button.doClick();
				}
			});

			button.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					String tutorialName = (String) list.getSelectedValue();
					Tutorial tutorial = Tutorials.newTutorial(
							"com.karimamin.tutorials", tutorialName);
					new JoglApplication(tutorial, tutorialName, 480, 320, false);
				}
			});

			add(list, BorderLayout.CENTER);
			add(button, BorderLayout.SOUTH);
		}
	}

 

And we’re done.  Run this and you should see a window open up that contains the list of all your tutorials which you can run.

 

To finish up, we’ll make a similar interface for the android.

Create a new android project, create the libs folder and import the required jars.

Link up the desktop project to this project so you can access the tutorial files

We then need to define a helper class that runs our tutorials.  Our main class will extend from ListActivity and thus we won’t be able to extend from AndroidApplication which is needed for our application to have access to the initialize function.  Therefore, create a new class that extends from AndroidApplication.

This class will get passed the tutorial when the activity is started.  So in the onCreate method, we want to read out the tutorial name from the bundle attached to the intent.

Next, we call Tutorials.newTutorial and pass it the tutorial name we just retrieved.  This should create a tutorial object which we can pass to initialize which in turn runs the tutorial passed to it.

With that done, in the default activity eclipse creates, change the class to extend from ListActivity as we are just going to display a list of available tutorials we can choose from.

In the onCreate method,  read out the list of names into a string array then call setListAdapter and pass in the list of names for the object array.  When done, your onCreate method should look similar to

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		String[] tutorials = Tutorials.getTutorialNames();

		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, tutorials));
	}

 

Next, we want to run a tutorial each time we click an item in the list.  To do so, we override the onListItemClick method to read out the item that was selected.  We then get the tutorial name from this item and package it into a bundle object so we can pass it to the helper class.

We do so by creating a new intent and passing the helper class for the second parameter.  Then set the extras method to the bundle containing the tutorial name and finally call startActivity passing in the intent to run.    Your code should look similar to:

	protected void onListItemClick(ListView listView, View view, int position, long id) {
		super.onListItemClick(listView, view, position, id);

		Object o = this.getListAdapter().getItem(position);
		String tutorialName = o.toString();

		Bundle bundle = new Bundle();
		bundle.putString("tutorial", tutorialName);
		Intent intent = new Intent(this, TutorialActivity.class);
		intent.putExtras(bundle);

		startActivity(intent);
	}

 

And that’s it.  If you right click on your android project and go to Run As->Android Application, you’ll see the list of tutorials that we will build on this site.

As before, you can download the files used for this tutorial here.

 

LibGDX Tutorial #2 My first sample app

Hi, welcome to Tutorial #2 of my LibGdx tutorials. We are going to continue from where we left off in tutorial #1 and actually draw something on the screen. In this tutorial, we will add functionality to the HelloLibGdx application so that whenever the mouse is clicked or the screen touched, the message “Hello from LibGdx” will be displayed.

If you have not done so, either run through tutorial #1 or grab the code from here.  Ready?  Let’s begin.

 

I. Reviewing the main Application Listener class

If you go into the java project and open up the HelloLibGDX class, you will see the following functions (may not be in this  order):

  • public void create() {}
  • public void dispose() {}
  • public void pause() {}
  • public void resize() {}
  • public void resume() {}
  • public void render() {}
Their functions are pretty obvious.  The create function is called when the application listener is created.  Dispose called when it’s destroyed.  Pause is called when your application is paused.  Resize and resume are called when you’re application is resized or resumed from a paused state.  The final function render is where all the work of your application is done.  It’s called when it’s time to display something on the screen.
So for this application, we are going to add some code to the render function.
First, let’s create some member variables and constants to hold information about the text we’re going to output.  Place these a the top of your class.
	private static final String textToDisplay = "Hello From LibGdx";
	private SpriteBatch spriteBatch;
	private BitmapFont font;
	private float textWidth;
	private float textHeight;
	private Vector<Point> v;
And inside the create function add
		spriteBatch  = new SpriteBatch();
		font = new BitmapFont();
		textWidth = font.getBounds(textToDisplay).width;
		textHeight = font.getBounds(textToDisplay).height;
		v = new Vector<Point>();
The first line is just a a string constant that has the text we wish to output.
The next line creates a “SpriteBatch” object.  This object is used to batch multiple “draw” calls into a single draw call.  Calling draw on something is expensive (in terms of time) and the less you call this function, the better.
The next line creates a BitmapFont object.  Bitmap fonts is an old technique for rendering text on the screen for games.  Typically, an image that consists of rows of characters (called a glyph)  is read by the BitmapFont object and outputs the characters based off the text passed to it.  The resulting graphic be scaled, flipped and colored.
The next two lines calculate the width and height of our text in pixels beforehand.  We don’t want to do this every time our “render” function is called.
Finally we need to store the list of points touched so that we can redraw the text each time the screen is “refreshed”.  When the screen is refreshed, the buffer is cleared out which removes everything that you see.  So we store the points in a list so that we can later draw them again.
Next, we want to add a simple nested class to hold our points
	class Point {
		public int x;
		public int y;
		public Point(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}
With all that set, we’re ready to draw our text.  So let’s modify the “render” function to output our text.

First we want to determine if the mouse button is held down (if a desktop application) or if a finger is touching the screen (android application).    We do this with a call to

		Gdx.input.isTouched();
This function checks to see if either the mouse has been clicked on the screen or if a finger has touched the screen.  If so, we need to grab the coordinates of the screen that was touched.  We do this by calling
Gdx.input.getX() for  the X coordinates
Gdx.input.getY() for the Y coordinates
Both these functions return an integer for the coordinates.
Once we get these two values, all we do is add the point to our list of points by
			positions.add(new Point(x,y));
After this, we start our drawing.  We first want to clear the screen.  The next two calls handle this.
		Gdx.graphics.getGL10().glClearColor(0, 0, 0, 0);
		Gdx.graphics.getGL10().glClear(Gdx.gl10.GL_COLOR_BUFFER_BIT);
The first sets what color we want to set the clear to be using RGBA notation.  The following function actually clears the screen to that particular color.  In our example, the screen is cleared to the color black (You’re left with just a black screen).
Following that, we need to output our text.
First, we tell sprite batch to start “recording” our draw calls.  We do this by specifying.
		spriteBatch.begin();
Then we need to loop through our list of points and draw them to the sprite batch.
		for (int i = 0; i < positions.size(); i++) {
			font.draw(spriteBatch, textToDisplay, positions.get(i).x - textWidth/2, Gdx.graphics.getHeight() - positions.get(i).y + textHeight / 2);
		}
One thing to note is that our coordinate system starts in the upper left corner and ends in the bottom right for the touch events but but for drawing we get the normal coord. system (lower left) starting to top right (end).  Thus we fix this by subtracting the y coordinate from the height of the window.  To make sure our text is centered exactly, we shift the x coordinates to the left by half the text width and we add (cause the system is in reverse) half the height.
Finally, we tell the sprite batch to render it’s buffer with a call to
		spriteBatch.end();
And that’s it!  If you run your program, you should see this whenever you click the mouse or touch the screen.

Figure 2-1

 

As usual, the project files for this tutorial are attached here.  Again, I did not store the libgdx jars in the zip to cut down on space.

 

LibGDX Tutorial #1

Hi, welcome to my first LibGDX tutorial.  There are a lot of example code on the web but there is not much documentation to help newbies such as myself.  Thus I decided to create a blog for everything I learn about LibGDX!

Before we start, let me explain a little about LibGDX.  What is LibGDX?

Well their website says the following:

“LibGDX is a cross-platform 2D and 3D game development framework written in Java/C/C++. It’s free for commercial and non-commercial use, pretty powerful and lots of fun to work with! Or at least no-one complained yet. Write your game once, deploy to Windows, Linux, Mac OSX and Android”

Basically, write a game and you’ll be able to run it a variety of platforms with just a few lines of code.  2 lines to be exact!  Wow that’s awesome!  In the following example, i’ll show you how you can create both a desktop and android application simultaneously.

OK let’s go on with the show!

I. Installing LibGDX

  1. To install LibGDX, you will want to download the latest nightly build from the site http://libgdx.l33tlabs.org/.
  2. Unzip the file into any folder of your choice.  In my example, I downloaded the files into a folder named “LibGDX”

II. Configuring your Eclipse Project

  1. Open up Eclipse and create a new Java Project.  Call it HelloLibGDX.  This is where we will create the desktop application and related files.
  2. Create a folder and label it “libs”. The folder must be called labeled “libs” as this is a requirement by LibGDX
  3. Inside this folder, you want to copy the following files from your LibGDX folder you extracted your files.
    • gdx.jar
    • gdx-backend-jogl.jar
    • gdx-backend-jogl-natives.jar
    • gdx-natives.jar
  4. Next, we need to link your project to the newly copied Jar files.  Do this by going into your project properties->Libraries->Add Jars and select all the jars you just copied over.

III. Writing the Code for a Desktop Application

  1. Still in your Java Project, create a new package under your source folder and name it com.hellolibgdx
  2. Create a new class HelloLibGDX and have it implement com.badlogic.gdx.ApplicationListener or you can just write ApplicationListener.  When the class is created, you should see something similar to

    package com.hellolibgdx;

    import com.badlogic.gdx.ApplicationListener;

    public class HelloLibGDX implements ApplicationListener {

    @Override
    public void create() {

    }

    @Override
    public void dispose() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void render() {

    }

    @Override
    public void resize(int arg0, int arg1) {

    }

    @Override
    public void resume() {

    }

    }

  3. Next, for each platform that we want to run our application on, we have to create a “Launcher” class.  This class sole responsibility is to launch the application on that platform.  So let’s create a new class named “DesktopLauncher” and create the normal public static void main function used to run java applications.
  4. Inside this function, we want to create a new instance of a JoglApplication which takes five(5) parameters.  The first parameter is an application listener  and in this case, we pass in a new instance of the  HelloLibGDX class.  The next argument is a string which represents the title of our application.  The next two arguments represent the width and height of our application in pixels.  We’ll set this to 480×320.    Finally, the last argument tells libgdx if we want to use OpenGL 2.0.  We’re going to use 1.0 for the majority of this tutorial so set this parameter to false.  You should be left with the following
    package com.hellolibgdx;
    import com.badlogic.gdx.backends.jogl.JoglApplication;/* Author: Karim Amin * This class will launch our application on our desktop environment */ public class DesktopLauncher {

    public static void main(String[] args) { new JoglApplication(new HelloLibGDX(), "Application Title", 480, 320, false);

    }

    }

  5. That’s it for the desktop portion.  If you save your work and right-click on your project and select Run->Java Application.  You should see the following:

    Sample Desktop Libgdx application

    Figure 1.1

IV. Writing Code for an Android Application

  1. Now, we’re going to create our android application.  All the work is pretty much done for us in the desktop portion of this tutorial.  So first, let’s create a new Android Project in Eclipse and name is HelloLibGDXAndroid
  2. We’ll use API 3 (Android 1.5) for the build target.  Set the application name to be “HelloLibGdx”.  Package name is com.hellolibgdx.  Set the activity name to be HelloLibGdxAndroidActivity
  3. As with the desktop project, we need to add a few jars to the project.  Again, create the libs folder as required and then copy the following files/folders into it:
    • gdx.jar
    • gdx-backend-android.jar
    • The entire folder armeabi
    • The entire folder armeabi-v7a
  4. Next, go to the project properties and hook up the jars again.  You will also need to link this project to the desktop project.  So go to the Projects tab, click Add and select the desktop project.
  5. Now we need to modify the HelloLibGdxAndroidActivity class to extend AndroidApplication instead of Activity.  The class AndroidApplication extends Activity already so specifying that is not necessary.
  6. Get rid of the setContentView statement and replace it with the line
    a call to initialize which takes two (2) parameters.  The first parameter is the main class which we will run.  You should instantiate a new instance of HelloLibGDX.  The second parameter again tells libgdx if we should use OpenGL 2.0 or not.  You will set this to false.  When done, you should have the following:

    package com.hellolibgdx;
    /* Author: Karim Amin
    * This is a sample android libgdx application
    */
    import android.os.Bundle;

    import com.badlogic.gdx.backends.android.AndroidApplication;

    public class HelloLibGdxAndroidActivity extends AndroidApplication {
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initialize(new HelloLibGDX(), false);
    }
    }

  7. Now you can run this by right clicking on your android project and going to Run As->Android Application, you should see the following:

    Sample Android libgdx application

  8. That’s it.  You have now created your first LibGdx application that runs on the desktop and on the android platforms.  Take a bow!

You can download a copy of the source files here in zip format.

 

MBTA Planner video posted on YouTube

View it now

 

How to open a URL in the default android web browser

private void openURL(String _url) {

startActivity(new Intent(Intent.ACTION_VIEW,
ContentURI.create(_url)));

}