banner



How To Make Small Android Games & Make Money

Android 2nd Game Tutorial for Beginners

  1. Introduction
  2. Create a Game Project
  3. Preparing Images and sounds
  4. Setting fullscreen (Version:1)
  5. Show character in the game (Version:two)
  6. Interact with histrion (Version: 3)
  7. Game with multiple characters (Version: four)
  8. Effects in the Game (Version: 5)
  9. Sound effects in game (Version: Release)

one- Introduction

This document is based on:

  • Android Studio 3.half-dozen.1

Target of the certificate is help you to become acquainted with a few simple techniques in  programming Android Game 2d. Include:

  • Use SuffaceView
  • Drawing on a Canvas
  • The motility of the game graphic symbol.
  • Interactions with the player's gestures

In this document, I volition guide you footstep by step, therefore, y'all need to read and practice upwardly to down. Nosotros volition write each version of the game from ane to the concluding version.

2- Create a Game Projection

On Android Studio create a new projection:

  • Proper noun: Android2DGame
  • Parcel name: org.o7planning.android2dgame

OK, your Projection was created.

Next you need to create an Action. On Android Studio select:

  • File > New > Activity > Empty Activeness

  • Activity Proper noun: MainActivity

Notation that you're creating a 2nd game on Android, so the interface of the game must exist drawn by you, and then y'all do not demand a activity_main.xml file.

3- Preparing Images and sounds

The Audio file of the explosion.

Background sound:

Right-click on the project "res" folder and cull:

  • New > Binder > Raw Resource Folder

Re-create these images to the drawable folder of project. Create raw binder, and copy explosion.wav & groundwork.mp3 to this folder.

4- Setting fullscreen (Version:1)

With games, yous demand to set the background paradigm and an important thing is that you demand to ready FullScreen style.

Your MainActivity class must extends from the Activity class .

MainActivity.java (Version: 1)

                                      package org.o7planning.android2dgame;   import android.app.Activity; import android.bone.Packet; import android.view.Window; import android.view.WindowManager;  public course MainActivity extends Activeness {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);          // Set up fullscreen         this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,                 WindowManager.LayoutParams.FLAG_FULLSCREEN);          // Fix No Title         this.requestWindowFeature(Window.FEATURE_NO_TITLE);      }  }                                  

Next, fix screen is Landscape. You demand to set inAndroidManifest.xml.

** AndroidManifest.xml **

                                      <?xml version="1.0" encoding="utf-viii"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     packet="org.o7planning.android2dgame">      <application         android:screenOrientation="landscape"         ... >         ...      </awarding>  </manifest>                                  

Running apps:

Notation: On Windows y'all can as well change the direction of the simulater by Ctrl + F11.

5- Show character in the game (Version:2)

Next you demand to write lawmaking to evidence the game character on the screen and movement it from left to correct in a certain speed.

With a character in the game you lot only have one image file, but the image are divided into several regions described the different deportment of the character.

Using the code y'all can draw a picture show to the Canvas of the game, at the x, y coordinates. Apply a  loop to continuously describe on the Sheet, you lot can create the move of the character.

When programming a game, you also need to pay attention to the movement direction of the characters in the game, the speed of the grapheme.

Create aGameobjectclass, objects of the game is extended from this class.

GameObject.java (Version: Release)

                                      package org.o7planning.android2dgame;  import android.graphics.Bitmap;  public abstract class GameObject {      protected Bitmap image;      protected final int rowCount;     protected final int colCount;      protected final int WIDTH;     protected final int HEIGHT;      protected last int width;       protected terminal int meridian;     protected int x;     protected int y;      public GameObject(Bitmap image, int rowCount, int colCount, int x, int y)  {          this.image = image;         this.rowCount= rowCount;         this.colCount= colCount;          this.10= x;         this.y= y;          this.WIDTH = image.getWidth();         this.Elevation = image.getHeight();          this.width = this.WIDTH/ colCount;         this.summit= this.Height/ rowCount;     }      protected Bitmap createSubImageAt(int row, int col)  {         // createBitmap(bitmap, x, y, width, height).         Bitmap subImage = Bitmap.createBitmap(prototype, col* width, row* height ,width,meridian);         return subImage;     }      public int getX()  {         return this.10;     }      public int getY()  {         return this.y;     }       public int getHeight() {         render meridian;     }      public int getWidth() {         return width;     }  }                                  

ChibiCharacter Class simulates a character in the game.

ChibiCharacter.java (Version: 2)

                                      package org.o7planning.android2dgame;  import android.graphics.Bitmap; import android.graphics.Sail;  public class ChibiCharacter extends GameObject {      individual static final int ROW_TOP_TO_BOTTOM = 0;     individual static concluding int ROW_RIGHT_TO_LEFT = 1;     private static final int ROW_LEFT_TO_RIGHT = 2;     private static final int ROW_BOTTOM_TO_TOP = iii;      // Row alphabetize of Prototype are being used.     private int rowUsing = ROW_LEFT_TO_RIGHT;      private int colUsing;      private Bitmap[] leftToRights;     private Bitmap[] rightToLefts;     private Bitmap[] topToBottoms;     individual Bitmap[] bottomToTops;      // Velocity of game graphic symbol (pixel/millisecond)     public static final bladder VELOCITY = 0.1f;      private int movingVectorX = 10;     individual int movingVectorY = five;      individual long lastDrawNanoTime =-1;      individual GameSurface gameSurface;      public ChibiCharacter(GameSurface gameSurface, Bitmap image, int x, int y) {         super(image, 4, three, ten, y);          this.gameSurface= gameSurface;          this.topToBottoms = new Bitmap[colCount]; // 3         this.rightToLefts = new Bitmap[colCount]; // three         this.leftToRights = new Bitmap[colCount]; // 3         this.bottomToTops = new Bitmap[colCount]; // iii          for(int col = 0; col< this.colCount; col++ ) {             this.topToBottoms[col] = this.createSubImageAt(ROW_TOP_TO_BOTTOM, col);             this.rightToLefts[col]  = this.createSubImageAt(ROW_RIGHT_TO_LEFT, col);             this.leftToRights[col] = this.createSubImageAt(ROW_LEFT_TO_RIGHT, col);             this.bottomToTops[col]  = this.createSubImageAt(ROW_BOTTOM_TO_TOP, col);         }     }      public Bitmap[] getMoveBitmaps()  {         switch (rowUsing)  {             case ROW_BOTTOM_TO_TOP:                 return  this.bottomToTops;             case ROW_LEFT_TO_RIGHT:                 return this.leftToRights;             example ROW_RIGHT_TO_LEFT:                 return this.rightToLefts;             example ROW_TOP_TO_BOTTOM:                 return this.topToBottoms;             default:                 return goose egg;         }     }      public Bitmap getCurrentMoveBitmap()  {         Bitmap[] bitmaps = this.getMoveBitmaps();         render bitmaps[this.colUsing];     }       public void update()  {         this.colUsing++;         if(colUsing >= this.colCount)  {             this.colUsing =0;         }         // Current time in nanoseconds         long at present = System.nanoTime();          // Never once did draw.         if(lastDrawNanoTime==-i) {             lastDrawNanoTime= now;         }         // Change nanoseconds to milliseconds (one nanosecond = 1000000 milliseconds).         int deltaTime = (int) ((now - lastDrawNanoTime)/ one thousand thousand );          // Distance moves         float altitude = VELOCITY * deltaTime;          double movingVectorLength = Math.sqrt(movingVectorX* movingVectorX + movingVectorY*movingVectorY);          // Summate the new position of the game character.         this.x = x +  (int)(distance* movingVectorX / movingVectorLength);         this.y = y +  (int)(distance* movingVectorY / movingVectorLength);          // When the game'south grapheme touches the edge of the screen, then change direction          if(this.x < 0 )  {             this.x = 0;             this.movingVectorX = - this.movingVectorX;         } else if(this.10 > this.gameSurface.getWidth() -width)  {             this.x= this.gameSurface.getWidth()-width;             this.movingVectorX = - this.movingVectorX;         }          if(this.y < 0 )  {             this.y = 0;             this.movingVectorY = - this.movingVectorY;         } else if(this.y > this.gameSurface.getHeight()- height)  {             this.y= this.gameSurface.getHeight()- height;             this.movingVectorY = - this.movingVectorY ;         }          // rowUsing         if( movingVectorX > 0 )  {             if(movingVectorY > 0 && Math.abs(movingVectorX) < Math.abs(movingVectorY)) {                 this.rowUsing = ROW_TOP_TO_BOTTOM;             }else if(movingVectorY < 0 && Math.abs(movingVectorX) < Math.abs(movingVectorY)) {                 this.rowUsing = ROW_BOTTOM_TO_TOP;             }else  {                 this.rowUsing = ROW_LEFT_TO_RIGHT;             }         } else {             if(movingVectorY > 0 && Math.abs(movingVectorX) < Math.abs(movingVectorY)) {                 this.rowUsing = ROW_TOP_TO_BOTTOM;             }else if(movingVectorY < 0 && Math.abs(movingVectorX) < Math.abs(movingVectorY)) {                 this.rowUsing = ROW_BOTTOM_TO_TOP;             }else  {                 this.rowUsing = ROW_RIGHT_TO_LEFT;             }         }     }      public void draw(Canvas canvas)  {         Bitmap bitmap = this.getCurrentMoveBitmap();         canvas.drawBitmap(bitmap,ten, y, null);         // Terminal depict time.         this.lastDrawNanoTime= System.nanoTime();     }      public void setMovingVector(int movingVectorX, int movingVectorY)  {         this.movingVectorX= movingVectorX;         this.movingVectorY = movingVectorY;     } }                                  

Game Thread is a thread that controls the update of the game interface.

GameThread.java (Version: Release)

                                      package org.o7planning.android2dgame;  import android.graphics.Sheet; import android.view.SurfaceHolder;  public course GameThread extends Thread {      private boolean running;     individual GameSurface gameSurface;     private SurfaceHolder surfaceHolder;      public GameThread(GameSurface gameSurface, SurfaceHolder surfaceHolder)  {         this.gameSurface= gameSurface;         this.surfaceHolder= surfaceHolder;     }      @Override     public void run()  {         long startTime = Arrangement.nanoTime();          while(running)  {             Canvass canvas= null;             try {                 // Get Canvas from Holder and lock it.                 canvass = this.surfaceHolder.lockCanvas();                  // Synchronized                 synchronized (canvas)  {                     this.gameSurface.update();                     this.gameSurface.describe(canvas);                 }             }grab(Exception e)  {                 // Do goose egg.             } finally {                 if(canvas!= null)  {                     // Unlock Canvas.                     this.surfaceHolder.unlockCanvasAndPost(sail);                 }             }             long now = System.nanoTime() ;             // Interval to redraw game             // (Change nanoseconds to milliseconds)             long waitTime = (now - startTime)/1000000;             if(waitTime < 10)  {                 waitTime= 10; // Millisecond.             }             System.out.print(" Wait Time="+ waitTime);              try {                 // Sleep.                 this.sleep(waitTime);             } catch(InterruptedException east)  {              }             startTime = Organization.nanoTime();             System.out.print(".");         }     }      public void setRunning(boolean running)  {         this.running= running;     } }                                  

GameSurfaceCourse simulate the unabridged surface of the game. This grade extends from SurfaceView, SurfaceView contains a Sheet object, the objects in the game volition exist drawn on the Canvass.

GameSurface.java (Version: 2)

                                      bundle org.o7planning.android2dgame;  import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Sheet; import android.view.SurfaceHolder; import android.view.SurfaceView;  public grade GameSurface extends SurfaceView implements SurfaceHolder.Callback {      individual GameThread gameThread;     private ChibiCharacter chibi1;      public GameSurface(Context context)  {         super(context);          // Brand Game Surface focusable so it can handle events. .         this.setFocusable(true);          // Sét callback.         this.getHolder().addCallback(this);     }      public void update()  {         this.chibi1.update();     }      @Override     public void draw(Canvas canvas)  {         super.draw(sheet);          this.chibi1.draw(canvas);     }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceCreated(SurfaceHolder holder) {         Bitmap chibiBitmap1 = BitmapFactory.decodeResource(this.getResources(),R.drawable.chibi1);         this.chibi1 = new ChibiCharacter(this,chibiBitmap1,100,50);          this.gameThread = new GameThread(this,holder);         this.gameThread.setRunning(true);         this.gameThread.start();     }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {      }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceDestroyed(SurfaceHolder holder) {         boolean retry= truthful;         while(retry) {             try {                 this.gameThread.setRunning(faux);                  // Parent thread must await until the end of GameThread.                 this.gameThread.join();             }grab(InterruptedException e)  {                 e.printStackTrace();             }             retry= truthful;         }     }  }                                  

MainActivity.coffee (Version: Release)

                                      package org.o7planning.android2dgame;  import android.app.Activity; import android.bone.Bundle; import android.view.Window; import android.view.WindowManager;  public course MainActivity extends Activity {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);          // Gear up fullscreen         this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,                 WindowManager.LayoutParams.FLAG_FULLSCREEN);          // Set No Title         this.requestWindowFeature(Window.FEATURE_NO_TITLE);          this.setContentView(new GameSurface(this));     }  }                                  

OK, 2nd version is completed, you can run the game.

6- Interact with histrion (Version: 3)

Adjacent, you can handle events when the user touches the screen, the game grapheme will run towards that you touched. You lot should handle this consequence on GameSurface course.

                                      @Override public boolean onTouchEvent(MotionEvent event) {     if (consequence.getAction() == MotionEvent.ACTION_DOWN) {         int x=  (int)outcome.getX();         int y = (int)result.getY();          int movingVectorX =10-  this.chibi1.getX() ;         int movingVectorY =y-  this.chibi1.getY() ;          this.chibi1.setMovingVector(movingVectorX,movingVectorY);         return true;     }     return simulated; }                                  

View full code:

GameSurface.java (Version: three)

                                      package org.o7planning.android2dgame;  import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView;  public form GameSurface extends SurfaceView implements SurfaceHolder.Callback {      individual GameThread gameThread;      private ChibiCharacter chibi1;      public GameSurface(Context context)  {         super(context);          // Brand Game Surface focusable so information technology can handle events.         this.setFocusable(true);          // Set callback.         this.getHolder().addCallback(this);     }      public void update()  {         this.chibi1.update();     }      @Override     public boolean onTouchEvent(MotionEvent event) {         if (event.getAction() == MotionEvent.ACTION_DOWN) {             int x=  (int)event.getX();             int y = (int)upshot.getY();              int movingVectorX =x-  this.chibi1.getX() ;             int movingVectorY =y-  this.chibi1.getY() ;              this.chibi1.setMovingVector(movingVectorX,movingVectorY);             return truthful;         }         render false;     }      @Override     public void draw(Canvas sheet)  {         super.draw(canvas);          this.chibi1.draw(sail);     }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceCreated(SurfaceHolder holder) {         Bitmap chibiBitmap1 = BitmapFactory.decodeResource(this.getResources(),R.drawable.chibi1);         this.chibi1 = new ChibiCharacter(this,chibiBitmap1,100,50);          this.gameThread = new GameThread(this,holder);         this.gameThread.setRunning(true);         this.gameThread.start();     }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {      }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceDestroyed(SurfaceHolder holder) {         boolean retry= true;         while(retry) {             effort {                 this.gameThread.setRunning(imitation);                  // Parent thread must wait until the end of GameThread.                 this.gameThread.bring together();             }catch(InterruptedException e)  {                 e.printStackTrace();             }             retry= true;         }     }  }                                  

Rerun the game:

seven- Game with multiple characters (Version: 4)

Y'all tin can add other characters to the game, here I add a secondary character. You demand to edit the code of theGameSurfac form:

GameSurface.coffee (Version: iv)

                                      package org.o7planning.android2dgame;  import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView;  import java.util.ArrayList; import java.util.Listing;  public class GameSurface extends SurfaceView implements SurfaceHolder.Callback {      private GameThread gameThread;      private final List<ChibiCharacter> chibiList = new ArrayList<ChibiCharacter>();      public GameSurface(Context context)  {         super(context);          // Make Game Surface focusable so it tin can handle events.         this.setFocusable(true);          // Set callback.         this.getHolder().addCallback(this);     }      public void update()  {         for(ChibiCharacter chibi: chibiList) {             chibi.update();         }     }      @Override     public boolean onTouchEvent(MotionEvent event) {         if (event.getAction() == MotionEvent.ACTION_DOWN) {             int x=  (int)effect.getX();             int y = (int)event.getY();              for(ChibiCharacter chibi: chibiList) {                 int movingVectorX =x-  chibi.getX() ;                 int movingVectorY =y-  chibi.getY() ;                 chibi.setMovingVector(movingVectorX, movingVectorY);             }             return truthful;         }         return false;     }      @Override     public void draw(Sail canvas)  {         super.draw(sheet);          for(ChibiCharacter chibi: chibiList)  {             chibi.draw(canvas);         }      }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceCreated(SurfaceHolder holder) {         Bitmap chibiBitmap1 = BitmapFactory.decodeResource(this.getResources(),R.drawable.chibi1);         ChibiCharacter chibi1 = new ChibiCharacter(this,chibiBitmap1,100,50);          Bitmap chibiBitmap2 = BitmapFactory.decodeResource(this.getResources(),R.drawable.chibi2);         ChibiCharacter chibi2 = new ChibiCharacter(this,chibiBitmap2,300,150);          this.chibiList.add(chibi1);         this.chibiList.add together(chibi2);          this.gameThread = new GameThread(this,holder);         this.gameThread.setRunning(truthful);         this.gameThread.beginning();     }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceChanged(SurfaceHolder holder, int format, int width, int peak) {      }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceDestroyed(SurfaceHolder holder) {         boolean retry= true;         while(retry) {             try {                 this.gameThread.setRunning(false);                  // Parent thread must await until the end of GameThread.                 this.gameThread.join();             }catch(InterruptedException east)  {                 eastward.printStackTrace();             }             retry= true;         }     }  }                                  

Rerun the game:

8- Effects in the Game (Version: v)

Sometime, you need to handle some furnishings of the game, for instance, y'all are steering a plane, when the plane hit the ground information technology will explode, so here explosion is an outcome. In this department, I will simulate when you click Chibi character, information technology volition explode.

Explosion Class simulate an explosion, when you click on the Chibi characte, it is removed from the game and an Explosion object volition be added to the game at position where Chibi graphic symbol has been eliminated.

Explosion.java (Version: 5)

                                      package org.o7planning.android2dgame;    import android.graphics.Bitmap; import android.graphics.Canvas;  public class Explosion extends GameObject {      individual int rowIndex = 0 ;     private int colIndex = -1 ;      private boolean finish= false;     private GameSurface gameSurface;      public Explosion(GameSurface GameSurface, Bitmap image, int x, int y) {         super(prototype, 5, 5, x, y);          this.gameSurface= GameSurface;     }      public void update()  {         this.colIndex++;          if(this.colIndex >= this.colCount)  {             this.colIndex =0;             this.rowIndex++;              if(this.rowIndex>= this.rowCount)  {                 this.cease= truthful;             }         }     }      public void draw(Canvas canvas)  {         if(!finish)  {             Bitmap bitmap= this.createSubImageAt(rowIndex,colIndex);             canvas.drawBitmap(bitmap, this.x, this.y,null);         }     }      public boolean isFinish() {         return finish;     }  }                                  

Change code of GameSurface class:

GameSurface.java (Version: 5)

                                      package org.o7planning.android2dgame;  import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView;  import java.util.ArrayList; import java.util.Iterator; import coffee.util.List;  public class GameSurface extends SurfaceView implements SurfaceHolder.Callback {      private GameThread gameThread;      private concluding List<ChibiCharacter> chibiList = new ArrayList<ChibiCharacter>();     private final List<Explosion> explosionList = new ArrayList<Explosion>();      public GameSurface(Context context)  {         super(context);          // Make Game Surface focusable so information technology tin can handle events.         this.setFocusable(true);          // Sét callback.         this.getHolder().addCallback(this);     }       @Override     public boolean onTouchEvent(MotionEvent event) {         if (consequence.getAction() == MotionEvent.ACTION_DOWN) {              int ten=  (int)result.getX();             int y = (int)event.getY();              Iterator<ChibiCharacter> iterator= this.chibiList.iterator();              while(iterator.hasNext()) {                 ChibiCharacter chibi = iterator.next();                 if( chibi.getX() < 10 && 10 < chibi.getX() + chibi.getWidth()                         && chibi.getY() < y && y < chibi.getY()+ chibi.getHeight())  {                     // Remove the electric current element from the iterator and the listing.                     iterator.remove();                      // Create Explosion object.                     Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.explosion);                     Explosion explosion = new Explosion(this, bitmap,chibi.getX(),chibi.getY());                      this.explosionList.add(explosion);                 }             }               for(ChibiCharacter chibi: chibiList) {                 int movingVectorX =x-  chibi.getX() ;                 int movingVectorY =y-  chibi.getY() ;                 chibi.setMovingVector(movingVectorX, movingVectorY);             }             return truthful;         }         return false;     }      public void update()  {         for(ChibiCharacter chibi: chibiList) {             chibi.update();         }         for(Explosion explosion: this.explosionList)  {             explosion.update();         }          Iterator<Explosion> iterator= this.explosionList.iterator();         while(iterator.hasNext())  {             Explosion explosion = iterator.next();              if(explosion.isFinish()) {                 // If explosion finish, Remove the current element from the iterator & list.                 iterator.remove();                 go along;             }         }     }      @Override     public void draw(Sheet sheet)  {         super.draw(canvas);          for(ChibiCharacter chibi: chibiList)  {             chibi.depict(canvas);         }          for(Explosion explosion: this.explosionList)  {             explosion.draw(canvas);         }      }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceCreated(SurfaceHolder holder) {         Bitmap chibiBitmap1 = BitmapFactory.decodeResource(this.getResources(),R.drawable.chibi1);         ChibiCharacter chibi1 = new ChibiCharacter(this,chibiBitmap1,100,l);          Bitmap chibiBitmap2 = BitmapFactory.decodeResource(this.getResources(),R.drawable.chibi2);         ChibiCharacter chibi2 = new ChibiCharacter(this,chibiBitmap2,300,150);          this.chibiList.add(chibi1);         this.chibiList.add(chibi2);          this.gameThread = new GameThread(this,holder);         this.gameThread.setRunning(true);         this.gameThread.start();     }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {      }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceDestroyed(SurfaceHolder holder) {         boolean retry= true;         while(retry) {             try {                 this.gameThread.setRunning(simulated);                  // Parent thread must wait until the end of GameThread.                 this.gameThread.join();             }take hold of(InterruptedException e)  {                 e.printStackTrace();             }             retry= truthful;         }     }  }                                  

Rerun the game:

ix- Sound effects in game (Version: Release)

Adjacent y'all need to add sound effects to the game, such as background sounds of the game, the sound of explosions when Chibi graphic symbol is destroyed.

Explosion.java (Version: Release)

                                      package org.o7planning.android2dgame;  import android.graphics.Bitmap; import android.graphics.Sail;  public class Explosion extends GameObject {      private int rowIndex = 0 ;     individual int colIndex = -1 ;      private boolean finish= false;     private GameSurface gameSurface;      public Explosion(GameSurface GameSurface, Bitmap epitome, int x, int y) {         super(image, 5, five, x, y);          this.gameSurface= GameSurface;     }      public void update()  {         this.colIndex++;          // Play audio explosion.wav.         if(this.colIndex==0 && this.rowIndex==0) {             this.gameSurface.playSoundExplosion();         }          if(this.colIndex >= this.colCount)  {             this.colIndex =0;             this.rowIndex++;              if(this.rowIndex>= this.rowCount)  {                 this.finish= true;             }         }     }      public void draw(Canvas canvas)  {         if(!finish)  {             Bitmap bitmap= this.createSubImageAt(rowIndex,colIndex);             canvas.drawBitmap(bitmap, this.x, this.y,null);         }     }      public boolean isFinish() {         return terminate;     }  }                                  

GameSurface.java (Version: Release)

                                      bundle org.o7planning.android2dgame;  import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvass; import android.media.AudioAttributes; import android.media.AudioManager; import android.media.SoundPool; import android.os.Build; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView;  import java.util.ArrayList; import java.util.Iterator; import java.util.Listing;  public class GameSurface extends SurfaceView implements SurfaceHolder.Callback {      private GameThread gameThread;      individual final List<ChibiCharacter> chibiList = new ArrayList<ChibiCharacter>();     private terminal List<Explosion> explosionList = new ArrayList<Explosion>();      private static final int MAX_STREAMS=100;     private int soundIdExplosion;     private int soundIdBackground;      private boolean soundPoolLoaded;     private SoundPool soundPool;        public GameSurface(Context context)  {         super(context);          // Brand Game Surface focusable so it tin handle events.         this.setFocusable(true);          // Sét callback.         this.getHolder().addCallback(this);          this.initSoundPool();     }      private void initSoundPool()  {         // With Android API >= 21.         if (Build.VERSION.SDK_INT >= 21 ) {              AudioAttributes audioAttrib = new AudioAttributes.Builder()                     .setUsage(AudioAttributes.USAGE_GAME)                     .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)                     .build();              SoundPool.Builder architect= new SoundPool.Builder();             builder.setAudioAttributes(audioAttrib).setMaxStreams(MAX_STREAMS);              this.soundPool = builder.build();         }         // With Android API < 21         else {             // SoundPool(int maxStreams, int streamType, int srcQuality)             this.soundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);         }          // When SoundPool load consummate.         this.soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {             @Override             public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {                 soundPoolLoaded = true;                  // Playing groundwork sound.                 playSoundBackground();             }         });          // Load the audio groundwork.mp3 into SoundPool         this.soundIdBackground= this.soundPool.load(this.getContext(), R.raw.background,1);          // Load the audio explosion.wav into SoundPool         this.soundIdExplosion = this.soundPool.load(this.getContext(), R.raw.explosion,1);       }      public void playSoundExplosion()  {         if(this.soundPoolLoaded) {             float leftVolumn = 0.8f;             bladder rightVolumn =  0.8f;             // Play sound explosion.wav             int streamId = this.soundPool.play(this.soundIdExplosion,leftVolumn, rightVolumn, 1, 0, 1f);         }     }      public void playSoundBackground()  {         if(this.soundPoolLoaded) {             float leftVolumn = 0.8f;             float rightVolumn =  0.8f;             // Play sound groundwork.mp3             int streamId = this.soundPool.play(this.soundIdBackground,leftVolumn, rightVolumn, 1, -1, 1f);         }     }      @Override     public boolean onTouchEvent(MotionEvent result) {         if (upshot.getAction() == MotionEvent.ACTION_DOWN) {              int x=  (int)issue.getX();             int y = (int)result.getY();              Iterator<ChibiCharacter> iterator= this.chibiList.iterator();               while(iterator.hasNext()) {                 ChibiCharacter chibi = iterator.next();                 if( chibi.getX() < x && 10 < chibi.getX() + chibi.getWidth()                         && chibi.getY() < y && y < chibi.getY()+ chibi.getHeight())  {                     // Remove the electric current element from the iterator and the list.                     iterator.remove();                      // Create Explosion object.                     Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.explosion);                     Explosion explosion = new Explosion(this, bitmap,chibi.getX(),chibi.getY());                      this.explosionList.add(explosion);                 }             }               for(ChibiCharacter chibi: chibiList) {                 int movingVectorX =x-  chibi.getX() ;                 int movingVectorY =y-  chibi.getY() ;                 chibi.setMovingVector(movingVectorX, movingVectorY);             }             return true;         }         return simulated;     }      public void update()  {         for(ChibiCharacter chibi: chibiList) {             chibi.update();         }         for(Explosion explosion: this.explosionList)  {             explosion.update();         }          Iterator<Explosion> iterator= this.explosionList.iterator();         while(iterator.hasNext())  {             Explosion explosion = iterator.next();              if(explosion.isFinish()) {                 // If explosion stop, Remove the current element from the iterator & listing.                 iterator.remove();                 keep;             }         }     }      @Override     public void depict(Canvas canvas)  {         super.draw(canvas);          for(ChibiCharacter chibi: chibiList)  {             chibi.draw(sheet);         }          for(Explosion explosion: this.explosionList)  {             explosion.draw(sail);         }      }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceCreated(SurfaceHolder holder) {         Bitmap chibiBitmap1 = BitmapFactory.decodeResource(this.getResources(),R.drawable.chibi1);         ChibiCharacter chibi1 = new ChibiCharacter(this,chibiBitmap1,100,50);          Bitmap chibiBitmap2 = BitmapFactory.decodeResource(this.getResources(),R.drawable.chibi2);         ChibiCharacter chibi2 = new ChibiCharacter(this,chibiBitmap2,300,150);          this.chibiList.add(chibi1);         this.chibiList.add together(chibi2);          this.gameThread = new GameThread(this,holder);         this.gameThread.setRunning(true);         this.gameThread.outset();     }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceChanged(SurfaceHolder holder, int format, int width, int peak) {      }      // Implements method of SurfaceHolder.Callback     @Override     public void surfaceDestroyed(SurfaceHolder holder) {         boolean retry= true;         while(retry) {             try {                 this.gameThread.setRunning(simulated);                  // Parent thread must wait until the stop of GameThread.                 this.gameThread.bring together();             }catch(InterruptedException e)  {                 eastward.printStackTrace();             }             retry= true;         }     }  }                                  

OK, at present you can rerun the game and listen to the sound furnishings of the game.

Note: You can refer to the documents on sound effects at:

Perhaps you are interested

These are online courses outside the o7planning website that nosotros introduced, which may include free or discounted courses.

Source: https://o7planning.org/10521/android-2d-game-tutorial-for-beginners

Posted by: rodriguezplad1987.blogspot.com

0 Response to "How To Make Small Android Games & Make Money"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel