Sunday , November 28 2021

Android Game Development Tutorial – Simple 2d Game Part 1 – Android Coding by DMTechnolab

Hello developers, I decided to post it Android game development tutorial. in this Android game development tutorial We are going to make a simple 2D game using Android Studio. We will not use any third party library or game engine for this Android game development tutorial. So let’s start.

Android game development with Unity

In this tutorial we are using Android Studio, and this is not really how real games are made in the industry. If you are really serious about mobile game development, and want to become a professional, or start your career in the game development industry; So you should learn some game engine. 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.

He said that the government has taken several steps to prevent such incidents.

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

Game story planning

Every game starts with a story. So you need to think. not actually 4 Because I have already decided what we are making.

So there will be one in our game Space jet, And Jet has to kill and kill enemies. There will be some good ones too and our space jet should not kill them. So basically if our space jet touches the other character being destroyed. So we just have to kill the enemies.

rules of the game

  • The player has to hit the ship after hitting the enemies.
  • If the player lets the 3 enemies go safely then the game is over.
  • If the player kills a good man then the game is over.

Android game development tutorial

We set the story and rules of the game. Now it’s time to make games. We will use Android Studio. And I think you all got Android Studio and know the basics.

Android game development tutorial – video demo

Before proceeding in this tutorial, you can watch this video to know what you will get at the end of it. Android game development tutorial part 1.

Android Game Development Tutorial – Live Demo

You can also download the APK for this part of the Android game development tutorial From the link given below.

Download apk

Download Used Images

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

Android game development images download

Create a new project

  • Open Android Studio and create a new project.
  • After loading the project you will get MainActivity.java And activity_main.xml
  • First paste all the pictures that you downloaded inside your project’s drawable folder.

Start screen design

Android game development tutorial

  • Above you can see the first screen of the game. It has a nice background image with two ImageButtons. You have 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-> value-> style. xml And modify it as the following code.
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

</resources>

  • inside activity_main.xml Write the following xml code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/splash"
    tools:context="net.simplifiedcoding.simplegame.MainActivity">

    <ImageButton
        android:id="@+id/buttonPlay"
        android:background="@drawable/playnow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/buttonScore"
        android:layout_centerHorizontal="true" />

    <ImageButton
        android:id="@+id/buttonScore"
        android:background="@drawable/highscore"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

  • When we tap play Now Button will begin our game activity.
  • Come in now MainActivity.java And write the following code.
package net.simplifiedcoding.simplegame;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    //image button
    private ImageButton buttonPlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //setting the orientation to landscape
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        //getting the button
        buttonPlay = (ImageButton) findViewById(R.id.buttonPlay);

        //adding a click listener
        buttonPlay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        
        //starting game activity
        startActivity(new Intent(this, GameActivity.class));
    }
}

  • Now you need to create a new activity called Game activity. To create a new activity Right click on package name -> New -> Activity -> Empty Activity

Building game view

Now it’s time to create our game view. We will use Surface view To watch our game. SurfaceView provides a dedicated drawing surface.

  • Create a new class named Gameview And write the following code.
public class GameView extends SurfaceView implements Runnable {

    //boolean variable to track if the game is playing or not 
    volatile boolean playing;
	
    //the game thread 
    private Thread gameThread = null;

	
    //Class constructor 
    public GameView(Context context) {
        super(context);	

    }

    @Override
    public void run() {
        while (playing) {
	    //to update the frame 
            update();
			
	    //to draw the frame 
            draw();
			
	    //to control 
            control();
        }
    }


    private void update() {

    }

    private void draw() {

    }

    private void control() {
        try {
            gameThread.sleep(17);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void pause() {
	//when the game is paused 
	//setting the variable to false 
        playing = false;
        try {
	    //stopping the thread 
            gameThread.join();
        } catch (InterruptedException e) {
        }
    }

    public void resume() {
	//when the game is resumed 
	//starting the thread again
        playing = true;
        gameThread = new Thread(this);
        gameThread.start();
    }
}

  • The above class is our GameView class. This is the actual game panel where we will play the game. Applying class Movable interface. we have a Floating variable boolean type variable is running This will track whether the game is going on. After that we GameThread, This is the main game loop. Then we have a constructor for the class. We are not doing anything inside the constructor right now. Then we have the override method Daud (), Here we are running a variable until the playing variable is Its going on What is true Inside the loop we are calling the following methods.
    Update () -> Here we will update the coordination of our characters.
    Draw () -> Here we will draw the characters on canvas.
    Control () -> This method will control the frames drawn per second. Here we are calling the delay method of the thread. And it is actually doing 60fps our frame rate aroud.
    After these we have two more ways.
    Pause () -> To stop the game, we are stopping GameThread here.
    Resume () -> To resume the game, here we are starting GameThread.

Add GameView to GameActivity

  • Now after tapping the play button, we are launching GameActivity. We will set our GameView to the contents of this activity. So go GameActivity.java And modify the code below.

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

package net.simplifiedcoding.spacefighter;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class GameActivity extends AppCompatActivity {

    //declaring gameview
    private GameView gameView;

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

        //Initializing game view object
        gameView = new GameView(this);

        //adding it to contentview
        setContentView(gameView);
    }

    //pausing the game when activity is paused
    @Override
    protected void onPause() {
        super.onPause();
        gameView.pause();
    }

    //running the game when activity is resumed
    @Override
    protected void onResume() {
        super.onResume();
        gameView.resume();
    }
}

Player making

  • Create a new class player inside your package and write the following code.
package net.simplifiedcoding.spacefighter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Created by Belal on 6/24/2016.
 */
public class Player {
    //Bitmap to get character from image
    private Bitmap bitmap;

    //coordinates
    private int x;
    private int y;

    //motion speed of the character
    private int speed = 0;

    //constructor
    public Player(Context context) {
        x = 75;
        y = 50;
        speed = 1;

        //Getting bitmap from drawable resource
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.player);
    }

    //Method to update coordinate of character
    public void update(){
        //updating x coordinate
        x++;
    }

    /*
    * These are getters you can generate it autmaticallyl
    * right click on editor -> generate -> getters
    * */
    public Bitmap getBitmap() {
        return bitmap;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getSpeed() {
        return speed;
    }
}

  • The above code is very easy to understand. I wrote comments to explain everything. So lets move forward.

Drawing Player for GameView

  • To pull the player into our GameView you have to return to the GameView.java class and modify it as below.
public class GameView extends SurfaceView implements Runnable {

    volatile boolean playing;
    private Thread gameThread = null;

    //adding the player to this class
    private Player player;

    //These objects will be used for drawing
    private Paint paint;
    private Canvas canvas;
    private SurfaceHolder surfaceHolder;

    public GameView(Context context) {
        super(context);

        //initializing player object
        player = new Player(context);

        //initializing drawing objects
        surfaceHolder = getHolder();
        paint = new Paint();
    }

    @Override
    public void run() {
        while (playing) {
            update();
            draw();
            control();
        }
    }

    private void update() {
        //updating player position
        player.update();
    }

    private void draw() {
        //checking if surface is valid
        if (surfaceHolder.getSurface().isValid()) {
            //locking the canvas
            canvas = surfaceHolder.lockCanvas();
            //drawing a background color for canvas
            canvas.drawColor(Color.BLACK);
            //Drawing the player
            canvas.drawBitmap(
                    player.getBitmap(),
                    player.getX(),
                    player.getY(),
                    paint);
            //Unlocking the canvas
            surfaceHolder.unlockCanvasAndPost(canvas);
        }
    }

    private void control() {
        try {
            gameThread.sleep(17);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void pause() {
        playing = false;
        try {
            gameThread.join();
        } catch (InterruptedException e) {
        }
    }

    public void resume() {
        playing = true;
        gameThread = new Thread(this);
        gameThread.start();
    }
}

  • Now try to execute your application. Put your emulator in landscape mode. When you tap on the Play Now button in the first activity, you will see the space jet shown below.
Android game development tutorial
Android game development tutorial

If you are getting the output as shown in the above picture then hooray! You might have got the concept about drawing a canvas using a surface view. And movement is the magic of coordinates. We are changing the x coordinates so that it is moving horizontally.

Now lets add our control Space jet.

Add control

Now we will add control to the player’s space jet. When the player taps on the screen, the space jet will rise up and the space jet will boost down after releasing the screen. The movement is inspired by the most popular sport flappy Bird.

To add this control, we need to detect the touch of the screen. So let’s start.

  • Get inside the GameView.java file and override the method OnTouchEvent ().
@Override
    public boolean onTouchEvent(MotionEvent motionEvent) {
        switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                //When the user presses on the screen
                //we will do something here 
                
                break;
            case MotionEvent.ACTION_DOWN:
                //When the user releases the screen 
                //do something here 
                break;
        }
        return true;
    }

  • Currently we need both these events which are just ACTION_UP And ACTION_DOWN. For what we need to do, we need to boost the space jet ACTION_UP And propels the space jet ACTION_DOWN.

Adding a booster to a space jet

Now we will add the booster Space jet So that our player can control Space jet. To do this, follow these steps.

  • Modify code of Player.java The file is as follows.
public class Player {
    private Bitmap bitmap;
    private int x;
    private int y;
    private int speed = 0;

    //boolean variable to track the ship is boosting or not
    private boolean boosting;

    //Gravity Value to add gravity effect on the ship
    private final int GRAVITY = -10;

    //Controlling Y coordinate so that ship won't go outside the screen
    private int maxY;
    private int minY;

    //Limit the bounds of the ship's speed
    private final int MIN_SPEED = 1;
    private final int MAX_SPEED = 20;

    public Player(Context context) {
        x = 75;
        y = 50;
        speed = 1;
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.player);

        //setting the boosting value to false initially
        boosting = false;
    }


    //setting boosting true
    public void setBoosting() {
        boosting = true;
    }

    //setting boosting false
    public void stopBoosting() {
        boosting = false;
    }

    public void update() {
        //if the ship is boosting
        if (boosting) {
            //speeding up the ship
            speed += 2;
        } else {
            //slowing down if not boosting
            speed -= 5;
        }
        //controlling the top speed
        if (speed > MAX_SPEED) {
            speed = MAX_SPEED;
        }
        //if the speed is less than min speed
        //controlling it so that it won't stop completely
        if (speed < MIN_SPEED) {
            speed = MIN_SPEED;
        }

        //moving the ship down
        y -= speed + GRAVITY;

        //but controlling it also so that it won't go off the screen
        if (y < minY) {
            y = minY;
        }
        if (y > maxY) {
            y = maxY;
        }
    }

    public Bitmap getBitmap() {
        return bitmap;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getSpeed() {
        return speed;
    }
}

  • We also need to find out the size of the screen so go inside GameActivity.java File and add the following code inside OnCreate ().
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Getting display object
        Display display = getWindowManager().getDefaultDisplay();

        //Getting the screen resolution into point object
        Point size = new Point();
        display.getSize(size);

        //Initializing game view object
        //this time we are also passing the screen size to the GameView constructor
        gameView = new GameView(this, size.x, size.y);

        //adding it to contentview
        setContentView(gameView);
    }

  • In the above code we are passing the screen size Gameview Constructor, so we also have to change Gameview the creator. So change Gameview Follow as creator.
public GameView(Context context, int screenX, int screenY) {
        super(context);

        //initializing player object
        //this time also passing screen size to player constructor
        player = new Player(context, screenX, screenY);

        //initializing drawing objects
        surfaceHolder = getHolder();
        paint = new Paint();
    }

  • In the above code you can see that we are sending the screen to the player constructor. So again we need to modify The player Class constructor.
public Player(Context context, int screenX, int screenY) {
        x = 75;
        y = 50;
        speed = 1;
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.player);

        //calculating maxY
        maxY = screenY - bitmap.getHeight();

        //top edge's y point is 0 so min y will always be zero
        minY = 0;

        //setting the boosting value to false initially
        boosting = false;
    }

  • Now come in to complete the booster GameView.java File and modify OnTouchEvent () as follows.
@Override
    public boolean onTouchEvent(MotionEvent motionEvent) {
        switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                //stopping the boosting when screen is released
                player.stopBoosting();
                break;
            case MotionEvent.ACTION_DOWN:
                //boosting the space jet when screen is pressed
                player.setBoosting();
                break;
        }
        return true;
    }

Now execute your application again to test the booster. If it is working fine then you can proceed.

Adding background stars

Now we will add background stars so that the background is animated.

package net.simplifiedcoding.spacefighter;

import java.util.Random;

/**
 * Created by Belal on 6/15/2016.
 */
public class Star {
    private int x;
    private int y;
    private int speed;

    private int maxX;
    private int maxY;
    private int minX;
    private int minY;



    public Star(int screenX, int screenY) {
        maxX = screenX;
        maxY = screenY;
        minX = 0;
        minY = 0;
        Random generator = new Random();
        speed = generator.nextInt(10);
        
        //generating a random coordinate 
        //but keeping the coordinate inside the screen size 
        x = generator.nextInt(maxX);
        y = generator.nextInt(maxY);
    }

    public void update(int playerSpeed) {
        //animating the star horizontally left side
        //by decreasing x coordinate with player speed 
        x -= playerSpeed;
        x -= speed;
        //if the star reached the left edge of the screen
        if (x < 0) {
            //again starting the star from right edge
            //this will give a infinite scrolling background effect
            x = maxX;
            Random generator = new Random();
            y = generator.nextInt(maxY);
            speed = generator.nextInt(15);
        }
    }

    public float getStarWidth() {
        //Making the star width random so that 
        //it will give a real look
        float minX = 1.0f;
        float maxX = 4.0f;
        Random rand = new Random();
        float finalX = rand.nextFloat() * (maxX - minX) + minX;
        return finalX;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

  • Come in now GameView.java And modify it as follows.
public class GameView extends SurfaceView implements Runnable {

    volatile boolean playing;
    private Thread gameThread = null;
    private Player player;

    private Paint paint;
    private Canvas canvas;
    private SurfaceHolder surfaceHolder;

    //Adding an stars list
    private ArrayList<Star> stars = new
            ArrayList<Star>();

    public GameView(Context context, int screenX, int screenY) {
        super(context);
        player = new Player(context, screenX, screenY);

        surfaceHolder = getHolder();
        paint = new Paint();

        //adding 100 stars you may increase the number
        int starNums = 100;
        for (int i = 0; i < starNums; i++) {
            Star s  = new Star(screenX, screenY);
            stars.add(s);
        }
    }

    @Override
    public void run() {
        while (playing) {
            update();
            draw();
            control();
        }
    }

    private void update() {
        player.update();

        //Updating the stars with player speed
        for (Star s : stars) {
            s.update(player.getSpeed());
        }
    }

    private void draw() {
        if (surfaceHolder.getSurface().isValid()) {
            canvas = surfaceHolder.lockCanvas();
            canvas.drawColor(Color.BLACK);

            //setting the paint color to white to draw the stars
            paint.setColor(Color.WHITE);

            //drawing all stars
            for (Star s : stars) {
                paint.setStrokeWidth(s.getStarWidth());
                canvas.drawPoint(s.getX(), s.getY(), paint);
            }

            canvas.drawBitmap(
                    player.getBitmap(),
                    player.getX(),
                    player.getY(),
                    paint);
            surfaceHolder.unlockCanvasAndPost(canvas);
        }
    }

    private void control() {
        try {
            gameThread.sleep(17);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void pause() {
        playing = false;
        try {
            gameThread.join();
        } catch (InterruptedException e) {
        }
    }

    public void resume() {
        playing = true;
        gameThread = new Thread(this);
        gameThread.start();
    }


    @Override
    public boolean onTouchEvent(MotionEvent motionEvent) {
        switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                player.stopBoosting();
                break;
            case MotionEvent.ACTION_DOWN:
                player.setBoosting();
                break;
        }
        return true;
    }
}

  • Now execute your app again. You will see an infinite scroll background this time as shown in the following image.
Android game development tutorial
Android game development tutorial

Add enemies

So far in Android game development tutorial, We’ve added our player, we’ve added an infinite scrolling background. We also added control over our player. Now we need to add some enemies. So let’s start coding the enemies.

  • Create a new Java class named Enemy and write the following code.
package net.simplifiedcoding.spacefighter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;

import java.util.Random;

/**
 * Created by Belal on 6/15/2016.
 */
public class Enemy {

    //bitmap for the enemy
    //we have already pasted the bitmap in the drawable folder
    private Bitmap bitmap;

    //x and y coordinates
    private int x;
    private int y;

    //enemy speed
    private int speed = 1;

    //min and max coordinates to keep the enemy inside the screen
    private int maxX;
    private int minX;

    private int maxY;
    private int minY;


    public Enemy(Context context, int screenX, int screenY) {
        //getting bitmap from drawable resource
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.enemy);

        //initializing min and max coordinates
        maxX = screenX;
        maxY = screenY;
        minX = 0;
        minY = 0;

        //generating a random coordinate to add enemy
        Random generator = new Random();
        speed = generator.nextInt(6) + 10;
        x = screenX;
        y = generator.nextInt(maxY) - bitmap.getHeight();

    }

    public void update(int playerSpeed) {
        //decreasing x coordinate so that enemy will move right to left
        x -= playerSpeed;
        x -= speed;
        //if the enemy reaches the left edge
        if (x < minX - bitmap.getWidth()) {
            //adding the enemy again to the right edge
            Random generator = new Random();
            speed = generator.nextInt(10) + 10;
            x = maxX;
            y = generator.nextInt(maxY) - bitmap.getHeight();
        }
    }



    //getters
    public Bitmap getBitmap() {
        return bitmap;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getSpeed() {
        return speed;
    }

}

  • We now need to add enemies to the GameView. So come inside GameView.java and modify the code as follows.
public class GameView extends SurfaceView implements Runnable {

    volatile boolean playing;
    private Thread gameThread = null;
    private Player player;

    private Paint paint;
    private Canvas canvas;
    private SurfaceHolder surfaceHolder;

    //Adding enemies object array
    private Enemy[] enemies;

    //Adding 3 enemies you may increase the size
    private int enemyCount = 3;

    private ArrayList<Star> stars = new
            ArrayList<Star>();

    public GameView(Context context, int screenX, int screenY) {
        super(context);
        player = new Player(context, screenX, screenY);

        surfaceHolder = getHolder();
        paint = new Paint();

        int starNums = 100;
        for (int i = 0; i < starNums; i++) {
            Star s = new Star(screenX, screenY);
            stars.add(s);
        }

        //initializing enemy object array
        enemies = new Enemy[enemyCount];
        for(int i=0; i<enemyCount; i++){
            enemies[i] = new Enemy(context, screenX, screenY);
        }
    }

    @Override
    public void run() {
        while (playing) {
            update();
            draw();
            control();
        }
    }

    private void update() {
        player.update();
        for (Star s : stars) {
            s.update(player.getSpeed());
        }

        //updating the enemy coordinate with respect to player speed 
        for(int i=0; i<enemyCount; i++){
            enemies[i].update(player.getSpeed());
        }
    }

    private void draw() {
        if (surfaceHolder.getSurface().isValid()) {
            canvas = surfaceHolder.lockCanvas();
            canvas.drawColor(Color.BLACK);

            paint.setColor(Color.WHITE);

            for (Star s : stars) {
                paint.setStrokeWidth(s.getStarWidth());
                canvas.drawPoint(s.getX(), s.getY(), paint);
            }

            canvas.drawBitmap(
                    player.getBitmap(),
                    player.getX(),
                    player.getY(),
                    paint);

            //drawing the enemies
            for (int i = 0; i < enemyCount; i++) {
                canvas.drawBitmap(
                        enemies[i].getBitmap(),
                        enemies[i].getX(),
                        enemies[i].getY(),
                        paint
                );
            }

            surfaceHolder.unlockCanvasAndPost(canvas);

        }
    }

    private void control() {
        try {
            gameThread.sleep(17);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void pause() {
        playing = false;
        try {
            gameThread.join();
        } catch (InterruptedException e) {
        }
    }

    public void resume() {
        playing = true;
        gameThread = new Thread(this);
        gameThread.start();
    }


    @Override
    public boolean onTouchEvent(MotionEvent motionEvent) {
        switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                player.stopBoosting();
                break;
            case MotionEvent.ACTION_DOWN:
                player.setBoosting();
                break;
        }
        return true;
    }
}

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

So we’re almost done on this part Android game development tutorial. Only the last thing is left. When our space jet touches the enemy, the enemy ship must explode. So we need a blast image and you can already find it inside your drawable folder. To show the blast image we need to detect a collision between the player and the enemy jet. So lets do this.

Collision detection

  • We will use the rect object to detect collisions. So come inside the enemy class modify the code.
public class Enemy {
    private Bitmap bitmap;
    private int x;
    private int y;
    private int speed = 1;

    private int maxX;
    private int minX;

    private int maxY;
    private int minY;

    //creating a rect object
    private Rect detectCollision;

    public Enemy(Context context, int screenX, int screenY) {
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.enemy);
        maxX = screenX;
        maxY = screenY;
        minX = 0;
        minY = 0;
        Random generator = new Random();
        speed = generator.nextInt(6) + 10;
        x = screenX;
        y = generator.nextInt(maxY) - bitmap.getHeight();

        //initializing rect object
        detectCollision = new Rect(x, y, bitmap.getWidth(), bitmap.getHeight());
    }

    public void update(int playerSpeed) {
        x -= playerSpeed;
        x -= speed;
        if (x < minX - bitmap.getWidth()) {
            Random generator = new Random();
            speed = generator.nextInt(10) + 10;
            x = maxX;
            y = generator.nextInt(maxY) - bitmap.getHeight();
        }

        //Adding the top, left, bottom and right to the rect object
        detectCollision.left = x;
        detectCollision.top = y;
        detectCollision.right = x + bitmap.getWidth();
        detectCollision.bottom = y + bitmap.getHeight();
    }

    //adding a setter to x coordinate so that we can change it after collision
    public void setX(int x){
        this.x = x;
    }

    //one more getter for getting the rect object
    public Rect getDetectCollision() {
        return detectCollision;
    }

    //getters
    public Bitmap getBitmap() {
        return bitmap;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getSpeed() {
        return speed;
    }

}

  • The same thing you need to do inside Player.java File.
public class Player {
    private Bitmap bitmap;
    private int x;
    private int y;
    private int speed = 0;
    private boolean boosting;
    private final int GRAVITY = -10;
    private int maxY;
    private int minY;

    private final int MIN_SPEED = 1;
    private final int MAX_SPEED = 20;

    private Rect detectCollision;

    public Player(Context context, int screenX, int screenY) {
        x = 75;
        y = 50;
        speed = 1;
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.player);
        maxY = screenY - bitmap.getHeight();
        minY = 0;
        boosting = false;

        //initializing rect object
        detectCollision =  new Rect(x, y, bitmap.getWidth(), bitmap.getHeight());
    }

    public void setBoosting() {
        boosting = true;
    }

    public void stopBoosting() {
        boosting = false;
    }

    public void update() {
        if (boosting) {
            speed += 2;
        } else {
            speed -= 5;
        }

        if (speed > MAX_SPEED) {
            speed = MAX_SPEED;
        }

        if (speed < MIN_SPEED) {
            speed = MIN_SPEED;
        }

        y -= speed + GRAVITY;

        if (y < minY) {
            y = minY;
        }
        if (y > maxY) {
            y = maxY;
        }

        //adding top, left, bottom and right to the rect object
        detectCollision.left = x;
        detectCollision.top = y;
        detectCollision.right = x + bitmap.getWidth();
        detectCollision.bottom = y + bitmap.getHeight();

    }

    //one more getter for getting the rect object
    public Rect getDetectCollision() {
        return detectCollision;
    }

    public Bitmap getBitmap() {
        return bitmap;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getSpeed() {
        return speed;
    }
}

  • Now to detect the collision, modify again inside the GameView.java file Update() The method is as follows.
private void update() {
        player.update();
        for (Star s : stars) {
            s.update(player.getSpeed());
        }

        for(int i=0; i<enemyCount; i++){
            enemies[i].update(player.getSpeed());

            //if collision occurrs with player
            if (Rect.intersects(player.getDetectCollision(), enemies[i].getDetectCollision())) {
                //moving enemy outside the left edge
                enemies[i].setX(-200);
            }
        }
    }

  • Execute the application again. You should see enemies hiding after a collision. Now after the collision we will show a blast image for the other part to look like destroying it.

Add blast effect

Now we are in the final stages for this part of it Android game development tutorial. We need to demonstrate an explosion effect after the collision.

We already have a burst image inside the drawable folder. We will use that image to display for a fraction of seconds after the collision. Then follow the following steps.

  • Create a new java class named Boom And write the following code.
package net.simplifiedcoding.spacefighter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Created by Belal on 6/15/2016.
 */
public class Boom {

    //bitmap object
    private Bitmap bitmap;

    //coordinate variables
    private int x;
    private int y;

    //constructor
    public Boom(Context context) {
        //getting boom image from drawable resource
        bitmap = BitmapFactory.decodeResource
                (context.getResources(), R.drawable.boom);

        //setting the coordinate outside the screen
        //so that it won't shown up in the screen
        //it will be only visible for a fraction of second
        //after collission
        x = -250;
        y = -250;
    }

    //setters for x and y to make it visible at the place of collision 
    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    //getters
    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

}

  • Now come back again GameView.java Follow the file and modify the code.
public class GameView extends SurfaceView implements Runnable {

    volatile boolean playing;
    private Thread gameThread = null;
    private Player player;

    private Paint paint;
    private Canvas canvas;
    private SurfaceHolder surfaceHolder;

    private Enemy[] enemies;

    private int enemyCount = 3;

    private ArrayList<Star> stars = new
            ArrayList<Star>();

    //defining a boom object to display blast
    private Boom boom;

    public GameView(Context context, int screenX, int screenY) {
        super(context);
        player = new Player(context, screenX, screenY);

        surfaceHolder = getHolder();
        paint = new Paint();

        int starNums = 100;
        for (int i = 0; i < starNums; i++) {
            Star s = new Star(screenX, screenY);
            stars.add(s);
        }

        enemies = new Enemy[enemyCount];
        for (int i = 0; i < enemyCount; i++) {
            enemies[i] = new Enemy(context, screenX, screenY);
        }

        //initializing boom object
        boom = new Boom(context);
    }

    @Override
    public void run() {
        while (playing) {
            update();
            draw();
            control();
        }
    }

    private void update() {
        player.update();

        //setting boom outside the screen
        boom.setX(-250);
        boom.setY(-250);

        for (Star s : stars) {
            s.update(player.getSpeed());
        }

        for (int i = 0; i < enemyCount; i++) {
            enemies[i].update(player.getSpeed());

            //if collision occurrs with player
            if (Rect.intersects(player.getDetectCollision(), enemies[i].getDetectCollision())) {

                //displaying boom at that location
                boom.setX(enemies[i].getX());
                boom.setY(enemies[i].getY());

                enemies[i].setX(-200);

            }
        }
    }

    private void draw() {
        if (surfaceHolder.getSurface().isValid()) {
            canvas = surfaceHolder.lockCanvas();
            canvas.drawColor(Color.BLACK);

            paint.setColor(Color.WHITE);

            for (Star s : stars) {
                paint.setStrokeWidth(s.getStarWidth());
                canvas.drawPoint(s.getX(), s.getY(), paint);
            }

            canvas.drawBitmap(
                    player.getBitmap(),
                    player.getX(),
                    player.getY(),
                    paint);

            for (int i = 0; i < enemyCount; i++) {
                canvas.drawBitmap(
                        enemies[i].getBitmap(),
                        enemies[i].getX(),
                        enemies[i].getY(),
                        paint
                );
            }

            //drawing boom image
            canvas.drawBitmap(
                    boom.getBitmap(),
                    boom.getX(),
                    boom.getY(),
                    paint
            );

            surfaceHolder.unlockCanvasAndPost(canvas);

        }
    }

    private void control() {
        try {
            gameThread.sleep(17);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void pause() {
        playing = false;
        try {
            gameThread.join();
        } catch (InterruptedException e) {
        }
    }

    public void resume() {
        playing = true;
        gameThread = new Thread(this);
        gameThread.start();
    }


    @Override
    public boolean onTouchEvent(MotionEvent motionEvent) {
        switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                player.stopBoosting();
                break;
            case MotionEvent.ACTION_DOWN:
                player.setBoosting();
                break;
        }
        return true;
    }
}

  • Now execute the application again and you will see an explosion effect on the collision.
Android game development tutorial
Android game development tutorial

Bingo! It is working perfectly fine. In case of any problem or confusion, you can download my source code. Unlock the download link to get its source code Android game development tutorial from below.

Android Game Development Part 1 – Source Code Download

Android Game Development Tutorial – Summary

This is a very simple and short game that we are making in it Android game development tutorial. This Android game development tutorial is a two-part series. This is the first part. In this section of this Android game development tutorial, we learned:

  • Surface view implementation
  • Drawing Characters on Canvas Using SurfaceView
  • Creating an infinite scroll background loop
  • Collision detection
  • Add control

In the next section -> Android game development tutorial part 2, We will complete the game by adding some text showing high scores and other game values ​​at the end. We will also add a game and some sound effects on the option.

Android Game Development Tutorial – Last Words

So this Android game development tutorial thats all for friends. This is a very long tutorial. Probably the longest I have posted so far. So try it carefully. And if you liked it, then share it among your friends. Android game development tutorial. Thank you 4


Source link

About dmtechnolab

Check Also

Simplified Coding

Android Espresso Tutorial – Testing Fragment in Isolation – Android Coding by DMTechnolab

Welcome to another tutorial in the Android test series. And this post is called Android …

Leave a Reply

Your email address will not be published. Required fields are marked *