Android Game Development Tutorial – Simple 2d Game Part 1

Hello developers, I decided to post this Android Game Development Tutorial. In this Android Game Development Tutorial we are going to create a simple 2d game using android studio. We will not be using any third party library or game engines for this android game development tutorial. So lets begin.

Android Game Development with Unity

In this tutorial we are using Android Studio, and really that is not how actual games are build in the industry. If you are really serious about Mobile Game Development, and want to become a professional, or want to start your career in Game Development Industry; then you must learn some Game Engines. And the best Game Engine to start as a Student is Unity. It is one of the most popular Game Engines. It is also free. And I have a Complete Free Course about building Android Games with Unity. Check it out Here.

But if you are just casual learner and just want to learn some basics with Android Studio, keep reading the post. 

Planning the Game Story

Every game start with a story. So you need to think. Not actually 😛 because I have already decided what we will be creating.

So In our game there will be a Space Jet, and the jet has to kill the enemies by hitting them. There will also be some good guys and our Space Jet should not kill them. So basically if our Space Jet  touches other character that will be destroyed. So we have to only kill the enemies.

The Game Rules

  • Player ship has to kill the enemies by colliding with them.
  • If player lets 3 enemies to go safely then the game is over.
  • If player kills a good guy the game is over.

Android Game Development Tutorial

We have decided the game story and the rules. Now its time to create the game. We will use Android Studio. And I am assuming all of you got Android Studio and know the basics of it.

Android Game Development Tutorial – Video Demo

Before going ahead in this tutorial you can check out this video to know what you will get at the end of this Android Game Development Tutorial part 1.

Android Game Development Tutorial – Live Demo

You can also download the apk for this part of Android Game Development Tutorial from the link given below.

Download APK

Download the Images Used

You can design and create your own character using Adobe Photoshop or other photo editing program. But if you don’t want to do it yourself you can download the images I used in this project from the link given below.

Android Game Development Images Download

Creating a New Project

  • Open Android Studio and create a new project.
  • Once the project is loaded you will get MainActivity.java and activity_main.xml
  • First paste all the images that you downloaded inside the drawable folder of your project.

Designing the Start Screen

android game development tutorial

  • Above you can see the first screen of the game. It has a nice background image with two ImageButtons. You already downloaded the images used in this screen.
  • As you can see it is a full screen activity. So to make your application full screen, you need to go res->values->styles.xml and modify it as the following code.

  • Inside activity_main.xml write the following xml code.

  • When we tap the Play Now button our Game Activity will start.
  • Now come inside MainActivity.java and write the following code.

  • Now you need to create a new activity named GameActivity. To create a new activity right click on the package name -> new -> activity -> empty activity

Building Game View

Now its time to build our Game View. We will be using SurfaceView for building our game view. Surfaceview provides a dedicated drawing surface.

  • Create a new class named GameView and write the following code.

  • The above class is our GameView class. It is the actual game panel where we will play the game. The class is implementing Runnable interface. We have a volatile boolean type variable running that will track whether the game is running or not. After that we have our gameThread, it is the main game loop. Then we have the constructor to the class. We are not doing anything inside the constructor right now. Then we have the overriden method run(), here we are running a loop until the playing variable running is true.  Inside the loop we are calling the following methods.
    update() -> Here we will update the coordinate of our characters.
    draw() -> Here we will draw the characters to the canvas.
    control() -> This method will control the frames per seconds drawn. Here we are calling the delay method of Thread. And this is actually making our frame rate to aroud 60fps.
    After these we have two more methods.
    pause() -> To pause the game, we are stopping the gameThread here.
    resume() -> To resume the game, here we are starting the gameThread.

Adding GameView to GameActivity

  • After tapping the play now button we are launching the GameActivity. We will set our GameView to the content of this activity. So go to GameActivity.java and  modify the code as below.

I will be adding the comments only above the new code added so that you can understand what is new in this code so that you can modify your code easily.

Creating Player

  • Create a new class Player inside your package and write the following code.

  • The above code is very easy to understand. I have written comments to explain everything. So lets move ahead.

Drawing Player to GameView

  • To draw the player to our GameView you need to come back to the GameView.java class and modify it as below.

  • Now try executing your application. Put your emulator in landscape mode. When you tap the play now button in the first activity you will see the moving Space Jet as shown below.
android game development tutorial
Android Game Development Tutorial

If you are getting the output as shown in the above image then Hurray!. You might have got the concept about drawing images in canvas using SurfaceView. And the movement is the magic of the coordinates. We are changing the x coordinate so it is moving horizontally ahead.

Now lets add control to our Space Jet.

Adding Controls

We will now add control to the player’s Space Jet. When the player will tap on the screen the Space Jet will boost up and after releasing the screen the Space Jet will boost down. The movement is inspired by the most popular game Flappy Bird.

To add this control we will need to detect touches of the screen. So lets begin.

  • Come inside GameView.java file and override the method onTouchEvent().

  • Currently we need these two events only which are ACTION_UP and ACTION_DOWN.  What we need to do is we need to boost up the Space Jet on ACTION_UP and boost down the Space Jet on ACTION_DOWN.

Adding Booster to Space Jet

Now we will add the booster to our Space Jet so that our player can control the Space Jet. Follow these steps to do this.

  • Modify the code of Player.java file as follows.

  •  We also need to detect the size of screen so go inside GameActivity.java file and add the following code inside onCreate().

  • In the above code we are passing screen size to GameView constructor, so we also need to change the GameView constructor. So change the GameView constructor as follow.

  • In the above code you can see we are passing the screen size to player constructor. So again we also need to modify the Player class constructor.

  • Now to complete adding the boosters come inside GameView.java file and modify the onTouchEvent() as follows.

Now execute your application again to test the boosters. If it is working fine then you can move ahead.

Adding Background Stars

Now we will add background stars to make the background looks animating.

  • Now come inside GameView.java and modify it as follows.

  • Now execute your app again. You will see a infinite scrolling background this time as shown in the following image.
android game development tutorial
Android Game Development Tutorial

Adding Enemies

So far in this Android Game Development Tutorial, we have added our player, we added an infinite scrolling background. We also added controls to our player. Now we need to add some enemies. So lets start coding the enemies.

  • Create a new java class named Enemy and write the following code.

  • We need to add the enemies in the GameView now. So come inside GameView.java and modify the code as follows.

  • Execute your application again and you should see the following output.
android game development tutorial
Android Game Development Tutorial

So we are almost done at this part of the Android Game Development Tutorial. Only the last thing is left. When our Space Jet touches the enemy, the enemy ship should blast. So we need a blast image and you already got it inside your drawable folder. To show the blast image we need to detect the collision between the player and enemy jet. So lets do this.

Detecting Collision

  • To detect collision we will use Rect object. So come inside Enemy class modify the code as follows.

  • The same thing you need to do inside the Player.java file.

  • Now to complete the collision detection, again to inside GameView.java file and modify the update() method as follows.

  • Again execute the app. You should see the enemies getting hidden after collision. Now after collision we will show a blast image for a fraction of second to make it look like destroying.

Adding Blast Effect

Now we are at the last phase for this part of this Android Game Development Tutorial. We need to display a blast effect after collision.

We already have a blast image inside the drawable folder. We will use that image to display for a fraction of second after the collision. So follow the following step.

  • Create a new java class named Boom and write the following code.

  • Now again come inside GameView.java file and modify the code as follow.

  • Now again execute the application and you will see a blast effect on collision.
android game development tutorial
Android Game Development Tutorial

Bingo! it is working absolutely fine. You can download my source code if having any troubles or confusion. Unlock the download link to get the source code of this Android Game Development Tutorial from below.

Android Game Development Part 1 – Source Code Download 

Android Game Development Tutorial – Summary

It is a really simple and small game we are creating in this Android Game Development Tutorial. This Android Game Development Tutorial is a two part series. This is the first part. In this part of this Android Game Development Tutorial we learnt:

  • SurfaceView implementation
  • Drawing Characters on Canvas using SurfaceView
  • Creating an Infinite Scroll Background Loop
  • Detecting Collision
  • Adding Controlls

In the next part -> Android Game Development Tutorial Part 2,  we will finally complete this game by adding some text displaying high score and other game values. We will also add a game over option and some sound effects.

Android Game Development Tutorial – Final Words

So thats all for this Android Game Development Tutorial friends. This is a really long tutorial. Probably the longest one I’ve posted so far. So try it carefully. And share it among your friends if you liked this Android Game Development Tutorial. Thank You 🙂

51 thoughts on “Android Game Development Tutorial – Simple 2d Game Part 1”

  1. Please also post for google cardboard 3D game in Android, Even I am looking for google cardboard widget Implementation.
    I will be really thankfull to you for this act of kindness.

    Reply
  2. Hi Bilal,
    I m always following your tutorials not other because of simplified code.
    Game tutorial is nice and i hope you will post other advanced 3D game tutorials too in your blog.
    May Allah bless you.

    Reply
  3. Hi,

    Can u help if i want enemies from top to bottom instead of right to left??
    How can i do that?? i tired myself but its not happening… 🙁

    Please help me admin or someone else…

    Reply
  4. Very nice tutorial, but you didn’t mention anything about the android manifest. While your creating intents to navigate from one activity to another you should modify the AndroidManifest.xml and add those activities.

    Reply
  5. Hi, i just did this tutorial up to creating / drawing the player there, when i tried to compile it, i got this:

    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: game2.cobain.com.coba2, PID: 3298
    java.lang.RuntimeException: Unable to start activity ComponentInfo{game2.cobain.com.coba2/game2.cobain.com.coba2.game}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)’ on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)’ on a null object reference
    at game2.cobain.com.coba2.game.onCreate(game.java:21)
    at android.app.Activity.performCreate(Activity.java:6664)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6077) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
    i am just confused how to figure this out, anyone can help?

    Reply
  6. GOt a bit of an issue. On an S5, the sprites don’t draw off screen – setting the X to -250 still shows them partially on the screen at the left side of the screen.

    Also, if a rocket is truck when idling at the bottom, that ship does not respawn until a click event happens again. It just sits there stuck at the end of the screen.

    Any ideas?

    Reply
    • Fixed it I think.

      -250 was too small of a value, I had to jump all of the off screen values up to -500 to get it to work as expected. Where does it look to see if an object exceeds x=0? The right edge, a corner, or where?

      Also, I’m wondering if showing how to do this in dp might be a good idea for devices of different screen densities. Just a suggestion.

      Great overall tutorial, helped me get conceptsa that a lot of other sites have bene making difficult.

      Reply
      • Create one boolean in enemy class, set to false when there is a collision.
        Then don’t draw the enemy which was collide/destroyed.

        Reply
  7. Hi sir,
    Thank u sir, I am doing projects in android by self. So this code is very helping to me by doing project. I am doing this code completely but after running the game seeing the error unfortunately closing app. In the logcat file, the error is seeing : Surface was not locked

    02-10 15:54:21.518 2733-3113/com.example.akhilasaleej.space_fighter E/AndroidRuntime: FATAL EXCEPTION: Thread-144
    Process: com.example.akhilasaleej.space_fighter, PID: 2733
    java.lang.IllegalStateException: Surface was not locked
    at android.view.Surface.unlockSwCanvasAndPost(Surface.java:298)
    at android.view.Surface.unlockCanvasAndPost(Surface.java:282)
    at android.view.SurfaceView$4.unlockCanvasAndPost(SurfaceView.java:863)
    at com.example.akhilasaleej.space_fighter.GameView.draw(GameView.java:98)
    at com.example.akhilasaleej.space_fighter.GameView.run(GameView.java:51)
    at java.lang.Thread.run(Thread.java:818)

    Reply
  8. great tutorial, really helped get me in the right direction for starting game development – covers the fundamentals I needed

    Reply
  9. Hello sir,
    This post is very use full for me and I also learn how to develop game in android studio.

    Thank you sir

    Reply
  10. Please Help!!
    Instead of the stars i need infinite scrolling background and floor…. This is my first Game so i don’t have any clue how to do it.
    Thanks in advance.

    Reply
  11. Hi Belal, first of all thank you very much for sharing your knowledges about android game dev, I ‘m totally new to this and this helped me a lot.

    I’ve followed your tutorial and succesfully re-created your game. But I have the app lagging when I move my mouse too much on the screen

    Actually I m trying to dev a new space fighter game, where the ship supposed to follow the finger touch. But when it comes to MotionEvent.ACTION_MOVE it seems there is too much threads on main.

    From what I ve investigated so far, a motionEvent.ACTION_CANCEL is triggered and the code enters in ViewGroup.dispatchTouchEvent. So it ends up making the app crash.

    Any idea ?

    Thanks in advance for your reply

    Reply
  12. hi ,
    the app was working fine…..but after adding boosting and clicking playnow it is stopping abruptly…can anyone help me with this

    Reply
  13. Thank you Mr. Belal Khan.
    I am a professor of computer technologies. I am 71 years old. I am from Peru.
    Your tutorial on a game is simply great. The code works immediately and the steps are very clear.
    Thanks again.

    Reply
  14. I cant get the first part to work and I think it’s my file structure in Android Studio. How does SurfaceView fit into the project? Is it supposed to be imported somewhere? I guess could you post a pic of how your files are structured in android studio that would help. Thanks

    Reply
  15. Since moving it offscreen to me is considered a hack, I use an ArrayList for my enemies. I then iterate through them with an iterator and then remove it if there is collision. One last step I do in my update method is to readd new enemies until I have MAX_ENEMIES once again.

    Basically, everytime I destroy a ship, another one pops out on the right side of the screen

    Reply
  16. Download link no longer works.
    I’m a high schooler desparate to take a sample of this code but I do not know where to put such classes on whatever areas. Please reply asap

    Reply
  17. Mr. Belal Khan

    I am trying to code the android game example, but download links and image files are no longer available.

    I appreciate your help.

    Reply
    • Yeah accidently the files are deleted and the local files from my computer also deleted, so I need to create the project again and share everything again. It will take some time, I will update all the links. Meanwhile you can follow the post or check my github repository.

      Reply
  18. Hi, I love your tutorial but your link you attach in this thread is die, please update it soon or maybe anyone have this file please upload it to google drive. Thank again.

    Reply
  19. Is there a youtube video available for this tutorial ? If yes, can you provide the link ? If no, can you a youtube video of this tutorial ?

    Reply

Leave a Comment