Android Game Development Tutorial

This tutorial has five parts:

Part 1: Building Android Application
Part 2: Integration with OpenGL and Designing a Splash Screen
Part 3: Under Construction
Part 4: Under Construction
Part 5: Under Construction

Part 1: Building Android Application

This is my first tutorial on android game development. Unlike other tutorials that cover only a limited range of topics, I will try to cover many things. I will be giving less explanation and more code. However, I will explain everything that you need to know and the common sources of errors. Before moving on, I must admit that I am aesthetically challenged. So you are welcome to improve the bitmaps, colors and style. I will appreciate if you can send me the modified better looking version of the application. I will give a lot of code therefore I am making the following assumptions for this tutorial:

  1. You have some knowledge of Java or at least object oriented languages.
  2. Experienced or willing to use Photoshop or any other software like it. If you want an open source software for photo editing GIMP is not a bad option.
  3. Basic knowledge about OpenGL.
  4. Have android SDK installed and integrated with the Eclipse IDE. There are many tutorials available on how to complete this step.
  5. Positively criticize any language and/or conceptual mistake in the tutorial.

Before, moving on I highly recommend you to go through android introductory documents by google. At least get a concept of:

  1. Activity
  2. Intent
  3. Manifest File
  4. Services

What I will do in this tutorial is to discuss step by step development of a game I named FunFight. It is nothing fancy but a simple 2D (possibly 3D in future) dog fight game. There is already a game with the name DogFight, therefore, I changed the name to FunFight. Let’s look at the overall plan for the development. The figure shows the steps I have in mind for the development.

I will add bitmaps and graphics wherever required. The (*.xcf) file for each bitmap is attached with the tutorial. You are more than welcome to improve the application aesthetically by modifying the graphics.

Step 1: Creating a New Project:

Open Eclipse and go to File->New->Project and select “Android Project” under the “Android”. Now create the project as shown in the following figure.

We are making a new project with the name “DogFight”. The minimum requirement for android SDK was set to “8”. An activity named “MainActivity” is created. This will become our main menu screen. Press “Finish” and Eclipse will generate all the necessary files. The important files of immediate importance are shown under the “Package Explorer” Tab:

Ok!!! let’s start to write the code behind the MainActivity. It is a lot easier than you may think. If we open the “MainActivity.java” file, the class “MainActivity” has only one function named “OnCreate”:

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

All it does is to attach a layout named “main” with this activity. This layout is defined in the “main.xml” file under the res->layout directory. The “R.layout.main” is the ID of the main.xml resource defined in “gen->com.asimmunawar.dogfight->R.java”. This file is auto generated and should not be edited manually. There is another important resource file in “res->layout->values”. This “strings.xml”. This XML should contain all the string values, colors, and dimensions that you want to use in your application. It is a lot better than hard coding the values. This helps if you want to translate your application in other languages and/or make other modifications. For the time being all I want is to add the text I want to show on the buttons and also add the background color that I want to assign. My “strings.xml” looks like:

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="app_name">Fun Fight</string>
	<string name="button_start_lbl">Start</string>
	<string name="button_help_lbl">Help</string>
	<string name="button_about_lbl">About</string>
	<string name="button_continue_lbl">Continue</string>
	<string name="button_quit_lbl">Quit</string>
		
	<color name="background">#6291c0</color>
</resources>
Now let’s create the layout. We will be creating what is known as a linear layout in Java. Anyone familiar with SWING should not have a problem understanding this layout. In this layout all the things are arranged in a vertical or horizontal fashion. This is defined with the “android:orientation” tab. Adding new buttons and label is simple. My “main.xml” looks like:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/background"
    android:padding="30dip"    
    >
<TextView android:id="@+id/label_title" android:layout_width="wrap_content" android:layout_height="wrap_content" 
android:text="@string/app_name" android:layout_gravity="center" android:textSize="35sp"  android:layout_marginBottom="25dip"></TextView>

<Button android:text="@string/button_start_lbl" android:id="@+id/button_start" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="@string/button_continue_lbl" android:id="@+id/button_continue" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="@string/button_about_lbl" android:id="@+id/button_about" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="@string/button_help_lbl" android:id="@+id/button_help" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="@string/button_quit_lbl" android:id="@+id/button_quit" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
Everything in this file is pretty self explanatory. The two important tags are “android:id” and “android:text”. The “android:id” tag simply sets the ID of object. This will be used to refer to this object in future. The “android:text” tag represents the text that will be displayed on the screen. Note that the text of the buttons is not hard coded. It is linked with the respective entries in the “strings.xml” file. We are ready to run the first version of our application. How easy was that. Just press the Run and this is what you should see.

If you don’t see this on the android emulator. You should search for the error you get on Google. Unless you are doing something extremely wrong, you should be able to find the answer on the Google. Anyways Here is the code for the current version.

Click here to download the code.

Step 2: Fancy Buttons and Logo

As we are designing a game therefore it should have a lot of bitmaps, fancy buttons, logo and animations. As I have already confessed that I am asthetically challenged, I will try to make the best bitmaps in my capacity. You can modify the *.xcf files to improve the graphics.

First let’s design the logo. I have made a logo by following a tutorial at (http://garmahis.com/tutorials/gimp-tutorials/ — A great resource indeed). To download the Logo’s xcf file click here.

Adding the logo bitmap to the screen is simple. First put the created PNG file in the “/res/drawable” folder. Now there are two ways to add this image. The easier way is to add an “ImageView” object in the layout file (main.xml) and add the following two lines in the MainActivity.java->OnCreate() function after “setContentView(R.layout.main);”.

ImageView main_image = (ImageView) findViewById(R.id.image_maintitle);
main_image.setImageResource(R.drawable.fun_fight);

I will discuss another way to add the image in the coming part of this tutorial. Note that R.drawable.fun_fight is an ID that was automatically attached with the bitmap. We can use this ID to identify fun_fight.png resource. Now let’s add bitmap buttons. There is nothing I hate more than the default buttons while developing a game. So I have designed simple bitmaps for the four states of the buttons ie. normal, pressed, selected and disabled. To download the gimp file of these images click here (buttons). In order to add the bitmaps to the buttons put the images in “/res/drawable” folder and then change add a file “button_menu.xml” to the same folder.

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:state_enabled="false"
	android:drawable="@drawable/button_disable" />
	<item android:state_enabled="true"
	android:state_pressed="true" android:drawable="@drawable/button_select" />
	<item android:state_enabled="true"
	android:state_focused="true" android:drawable="@drawable/button_select" />
	<item android:state_enabled="true"
	android:drawable="@drawable/button" />
</selector>

The file is self explanatory. We just assign each image to a button state. Now we have to make some changes in the main.xml file. Change each button entry in the main.xml to this:

<Button android:id="@+id/button_start"
android:text="@string/button_start_lbl"
android:textSize="@dimen/menu_buttons_text_size"
android:textColor="@color/menu_buttons"
android:textStyle="bold"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15px"
android:layout_marginRight="15px"
android:layout_marginTop="0px"
android:background="@drawable/button_menu"/>

and that’s all. We have successfully added buttons and logo bitmap to our project. The output should look like.

As we can see the bitmaps for the buttons are deformed. There is a very simple and magical solution from Google called 9patch. draw9patch is a simple tool that comes with the Android SDK. All it does is to virtually divide the image into 9 parts. The OS knows which parts of the image should be stretched in case or resizing and which parts should be kept as they are. For details about this tool search 9 patches android on Google. The output of the tool is another png file with .9 appended in its name. button.png changes to button.9.png and so on. The great thing is that we do not need to make any changes in the code. OS automatically checks if there is a file with .9 extension. So just by replacing the original images with there .9 versions does the trick. NOTE: Delete the original bitmaps after creating their respective .9 versions. Else the OS gets confused and give errors in compilation. The new output looks like.

We can also add a background image to the screen. The image I am using can be downloaded from here (back ground image). The image can be added to the background by changing the background tag in the main.xml to android:background=”@drawable/bk_gnd”. Of course you need to copy the bk_gnd.png in the drawable folder before running your application. Moreover, I have created some small animations. Whenever, a menu button is pressed it increases in size momentarily and then again shrinks to its original size. This animation is defined in /res/anim/menu_button_anim.xml file.

<?xml version="1.0" encoding="utf-8"?>

<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXScale="1" 
    android:toXScale="1.05"
    android:fromYScale="1" 
    android:toYScale="1.05" 
    android:pivotX="50%"
    android:pivotY="50%" 
    android:startOffset="0" 
    android:duration="400"
    android:fillBefore="true"
/>

The animation must be loaded and assign to the view. startAnimation() function is a part of every view and therefore any view in android can be animated. The procedure for applying animation to a button, textbox or any other object is exactly the same. Add the following to the MainActivity.java.

public class MainActivity extends Activity implements OnClickListener {
    
	Animation anim_menu_button;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		anim_menu_button = AnimationUtils.loadAnimation( this, R.anim.menu_button_anim );
	
		final Button btn_start = (Button) findViewById(R.id.button_start);
		btn_start.setOnClickListener(this);
	
		ImageView main_image = (ImageView) findViewById(R.id.image_maintitle);
		main_image.setImageResource(R.drawable.fun_fight);
	}
	
	public void onClick(View v) {
		v.startAnimation(anim_menu_button);
	}
}

Now whenever you will press the start button you will be able to see the animation. Add a listener to all the buttons and you will get the same animation for all. I have added another animation. It is a blurred line that keeps on moving horizontally on the background gives a nice animated background. The respective animation is defined in this xml file.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

	<scale
	    android:fromXScale="1" 
	    android:toXScale="1"
	    android:fromYScale="400" 
	    android:toYScale="400" 
	    android:pivotX="50%"
	    android:pivotY="0%" 
	    android:startOffset="0" 
	    android:duration="3"
	    android:fillBefore="true"
	    android:fillAfter="false"/>
	
	<rotate
	    android:fromDegrees="20"
	    android:toDegrees="20"
	    android:duration="3"
	    android:pivotX="0%"
	    android:pivotY="0%" />
	
	<translate
	    android:fromXDelta="-100"
	    android:toXDelta="500"
	    android:fromYDelta="-150"
	    android:toYDelta="-150"
	    android:duration="2000"
	    android:zAdjustment="top" 
	    android:repeatCount="100"/>
</set>

I cannot show the animations in pictures therefore download the code at the end of this page and see for yourself.

Step 3: About and Help dialog boxes

Each screen in the application is essentially and Activity. So we will need to create two activities one for each dialog box. I will only discuss the about dialog box. First lets create a new layout about.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:padding="10dip">
    <TextView android:id="@+id/about_content"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="@string/about_text" />
</ScrollView>

The text is set to @string/about_text which is defined in strings.xml. As explained before this is much better approach than hard coding the text. The layout is complete. Now we need to add the activity class. Add a new class AboutActivity.java and add the following code in it.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:padding="10dip">
    <TextView android:id="@+id/about_content"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="@string/about_text" />
</ScrollView>

Now we need to create an intent to start the new activity this can be done by adding the following code in the OnClick() function of MainActivity.java.

public void onClick(View v) {
	v.startAnimation(anim_menu_button);

	switch (v.getId()) {
    case R.id.button_start:
    	break;    
    case R.id.button_continue:
        break;
    case R.id.button_about:
        Intent i_about = new Intent(this, AboutActivity.class);
        startActivity(i_about);
        break;    
    case R.id.button_help:
        Intent i_help = new Intent(this, HelpActivity.class);
        startActivity(i_help);
        break;
    case R.id.button_quit:
    	System.exit(RESULT_OK);
    	break;
    }
}

That’s it. But before running the project we need to make the entry in the manifest file. Add the following lines in the AndroidManifest.xml file and you are good to go.

<activity android:name=".AboutActivity" android:label="@string/about_title" android:theme="@android:style/Theme.Dialog"></activity>

The screen should look like.

When the about button is pressed.

Click here (Step 3) to download the code up till this step.


Acknowledgments:

I have used the following tutorials in building this part of the application.

  1. Robert Greens DIY (http://www.rbgrn.net/content/54-getting-started-android-game-development)
  2. Conway’s Game of Life (http://www.quesucede.com/page/show/id/conway_game_of_life_android)
  3. Fancy buttons (http://www.thesecretpie.com/2010/07/creating-custom-fancy-buttons-in.html)
  4. 70 creative GIMP tutorials (http://garmahis.com/tutorials/gimp-tutorials/)

2 comments

No ping yet

  1. Chard says:

    Nice tutorials dude.. could you make a tutorials about tiled base scrolling map. Thanks and more power.

  2. gaurav says:

    very good tutorial…learned a lot. plz update the Under construction part soon….

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>