Click here to Skip to main content
Click here to Skip to main content

Simple Android Ball Game

By , 29 Apr 2011
 

Introduction

This is a tutorial for developing a Ball Game in Android OS. It will introduce you to developing Android games using AndEngine (free Android 2D open source game engine). To understand this tutorial, you will need to have some basic knowledge about AndEngine and programming in Java. If you don't have knowledge about AndEngine, you should check this link. The goal of this tutorial is to teach you how to make your own Android game.

The Game

It's a classic game idea implemented in a modern way. You control the ball using the accelerometer sensor and your goal is to collect all "diamonds", avoid enemy balls and to come safely to the end.

pic1.jpg

pic2.jpg

pic3.jpg

pic4.jpg

What You Need to Start?

To start developing your own Android games, you need SDK and game engine (it will make your life way easier!). I used Eclipse SDK and game engine called AndEngine. Are you wondering how to setup Eclipse SDK and AndEngine together? Click on the link to see "Getting started with AndEngine" tutorial.

Let's Do Some Coding!

Let's see what is hiding in the code! Please note that I didn't paste the full source code here. I just pasted some snippets. You can download the full project to see the complete source code.

First, we will take a short tour in the main class.

public class GameLogicController extends BaseGameActivity 
	implements IAccelerometerListener{
                 public PlayerProfileManager playerProfileManager; 
                 public LevelController levelController;
                 private Camera camera;
                 protected PhysicsWorld mPhysicsWorld;
                 public Texture mTexture;
                 public TextureRegion enemyTextureRegion;
                 private float mGravityX;
                 private float mGravityY;
                 private final Vector2 mTempVector = new Vector2();
                 public TiledTextureRegion mCircleFaceTextureRegion;
                 private RepeatingSpriteBackground mGrassBackground;
                 private Sound mGameOverSound;
                 ...
}

GameLogicController is the base class in our game, BaseGameActivity is the base class in AndEngine and IAccelerometerListener is the interface used to get data from your mobile phone accelerometer sensor. PlayerProfileManager and LevelController are just some game classes that you will know later.

@Override
public Engine onLoadEngine() {
	...

	levelController.mCameraWidth = 460;
	levelController.mCameraHeight = 320;
	camera = new Camera(0, 0, levelController.mCameraWidth, 
			levelController.mCameraHeight);
	return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, 
	new RatioResolutionPolicy(levelController.mCameraWidth, 
	levelController.mCameraHeight), camera).setNeedsSound(true));  
}

Method onLoadEngine creates a new game engine. First, we need to create Camera for declaring the screen resolution. An important and very useful thing is that Camera resolution isn't connected with mobile phone resolution. That will save you really a lot of work with graphics positions! For example, we declared screen resolution 460x320. You don't need to take care about mobile phone resolution, because you will always use AndEngine resolution (460x320) and AndEngine will automatically recalculate AndEngine resolution to real mobile phone resolution. The next step is to create new Engine. You just need to declare screen orientation (landscape or portrait), screen resolution and custom options. We used only one custom option, for enabling sound.

public Scene newGameLevelScene(int levelId){
	Scene scene = new Scene(2);
	this.mPhysicsWorld = new FixedStepPhysicsWorld(60, new Vector2(0, 0), false);
	levelController.setScene(scene);
	levelController.setmPhysicsWorld(mPhysicsWorld);
	levelController.createFrame();
	levelController.loadLevel(levelId);
	this.enableAccelerometerSensor(this);
	scene.registerUpdateHandler(this.mPhysicsWorld);
	return scene;
}

Here, you can see four very important things. First, we need to create a new display Scene and FixedStepPhysicWorld. FixedStepPhysicWorld is a 2D simulation of real world physic model. It's used for calculating gravity, collision detection... Let's focus on PhysicWorld. It takes three parameters. The first one is frames per seconds (how many times per second should screen be refreshed), the second is gravity vector and third is just if we want to allow PhysicWorld sleeping. At the end, we need to set enableAccelerometerSensor and registerUpdateHandler.

@Override
public void onAccelerometerChanged(AccelerometerData pAccelerometerData) {
		this.mGravityX = pAccelerometerData.getY() * 2;
		this.mGravityY = pAccelerometerData.getX() * 2;
		if(this.mGravityX > con)
			this.mGravityX = con;
		if(this.mGravityY > con)
			this.mGravityY = con;
		if(this.mGravityX < con * (-1))
			this.mGravityX = con * (-1);
		if(this.mGravityY < con * (-1))
			this.mGravityY = con * (-1);
		this.mTempVector.set(this.mGravityX, this.mGravityY);
		this.mPhysicsWorld.setGravity(this.mTempVector);
	}

In method newGameScene, we enabled accelometerSensor that controls method onAccelerometerChanged. This method is called whenever accelerometer is changed.

protected Scene createQuitScene() {
		
	Scene scene = new Scene(2);
	scene.setBackground(this.mMenuBackground);
	Sprite buttonLevel = new Sprite(100, 100, 250, 70, this.mMenuOkTextureRegion)
	{
		@Override
		public boolean onAreaTouched
		(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, 
		float pTouchAreaLocalY)
		{
			if(checkTouchTime())
				GameLogicController.getInstance().finish();
			
			return true;
		}
	};
		
	scene.registerTouchArea(buttonLevel);
	scene.getTopLayer().addEntity(buttonLevel);
	...
} 

Sprite is just graphic on the scene. Much more interesting is the method onAreaTouched. It is callback and whenever someone will press on the button (sprite), this method will be called. Don't forget to register touch area (registerTouchArea) and to add button (addEntity) to the scene!

We just finished with the main class, so we can move to the LevelController class.

public class LevelController   {
        private ArrayList<Shape> enemyList;
	private ArrayList<Shape> goodsList;
	private ArrayList<Shape> endPointList;
        ...

public void createPlayer(TiledTextureRegion mCircleFaceTextureRegion, int x, int y){
	//mPlayer = new Player(x, y, mCameraHeight/10,mCameraHeight/10,
	mCircleFaceTextureRegion, this);
	mPlayer = new Player(x, y, 30,30,mCircleFaceTextureRegion, this);
	FixtureDef FIXTURE = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
	Body body;
	body = PhysicsFactory.createCircleBody(mPhysicsWorld, mPlayer, 
	BodyType.DynamicBody, FIXTURE);
	
	mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector
	(mPlayer, body, true, true, false, false));
	scene.getTopLayer().addEntity(mPlayer);		
     }
...
}

LevelController class is responsible for loading levels and controlling level events. Arraylists enemyList, goodsList and endPointList are used for storing enemy balls, goods (diamonds) and end points (finish line). Method createPlayer creates a new player on position x,y with size 30x30, PhysicFactory.CreateFixtureDef creates a new physical object. Physical object should be registered to mPhysicsWorld for collision detection.

public void callbackCollisionGoods(int i){
		Shape goodShape = goodsList.get(i);
		scene.getBottomLayer().removeEntity(goodShape);
		goodsList.remove(i);
	}

If player collects diamond, callbackCollisionGoods is called. In this method, we remove diamond from goodsList and goodShape from scene.

Other methods in this class are very similar and I won't describe them in detail.

The next class is PlayerProfileManager. In this class, you will find only basic Java code except method WriteSettings.

private void WriteSettings() {
	String FILENAME = "settings2";
	FileOutputStream fos = null;
	DataOutputStream dos;

	try {
		fos = gameLogicController.openFileOutput(FILENAME, Context.MODE_PRIVATE);
	} catch (FileNotFoundException e) {			
	}
	try {
		dos=new DataOutputStream(fos);
		
		dos.writeInt(unlockedLevelId);	
	} catch (IOException e) {
	}
	try {
		fos.close();
	} catch (IOException e) {
	}
}

In method WriteSettings, we save level information to mobile phone. It's necessary to open, write and close file. Actually, we save only one number - ID of last unlocked level. For example, if level ID is 5, then levels 1, 2, 3, 4 and 5 are unlocked.

The last described class is Player.

public class Player extends AnimatedSprite   {
...
@Override
	protected void onManagedUpdate(final float pSecondsElapsed) {
		super.onManagedUpdate(pSecondsElapsed);
		onBeforePositionChanged();
	}

private boolean onBeforePositionChanged(){
		
	//speed up
	if(frameCount < 2){
		frameCount++;
		return true;
	}
	frameCount = 0;
		
	int enemyListSize = levelController.getEnemyList().size();
	for(int i = 0; i < enemyListSize; i++)
		if(this.collidesWith(levelController.getEnemyList().get(i)))
		{
			levelController.callbackCollisionEnemy();
			return false;
		}
	for(int i = 0; i < levelController.getGoodsList().size(); i++)
		if(this.collidesWith(levelController.getGoodsList().get(i)))
		{
			levelController.callbackCollisionGoods(i);
			return false;
		}

	for(int i = 0; i < levelController.getEndPointList().size(); i++)
		if(this.collidesWith(levelController.getEndPointList().get(i)))
		{
			levelController.callbackCollisionWithEndPoint();
			return false;
		}
	return true;
    }
...
} 

Player class is extended AnimatedSprite. The difference between Sprite and AnimatedSprite is just one - animated sprite consists of more pictures (animation) while Sprite consist of one picture. OnManagedUpdate is callback executed every "x" miliseconds. OnBeforePositionChanged checks if player is in collision with enemy, diamond or end point. If it's in collision, then the appropriate callback is executed.

Android Game Developing

I hope you see that Android game developing isn't too hard. With some practice, you can develop your Android dream game. At the end of the tutorial, I would like to thank you for your attention. This is my first article and I would be really glad if you give me any feedback.

History

  • 29 April, 2011- Article uploaded

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sašo Mađarić
Slovenia Slovenia
Member
I'm Sašo Mađarić, student in master course of the computer scient in university FERI Maribor, Slovenia. I have knowledge programming languages like C, C++, Java, C#, Adobe Flash/Flex, Objective C 2.0, js, php... I have couple of years experiences with developing software for some slovenian companies, but i also worked in private university PUC Minas Gerais located in Belo Horizonte, Brazil. I'm interested in many areas, like artificial intelligence, image processing, development of computer games, information systems... For more informations please contact me by email.
 
Also, in my free time i like to take some pictures... some of them you can see at
 
http://www.flickr.com/people/saso_madaric/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberMember 1006347219 May '13 - 12:17 
nice.
Questionmultiple sliding window i n one activitymemberSanjay22Tomar18 Apr '13 - 0:51 
hello everyone,
 
I am working in a project for client. I have to create multiple shutter in one activity like sliding window. so plz tell me full source code..
Thanks.
AnswerRe: multiple sliding window i n one activitymembersujeet878818 Apr '13 - 0:53 
hi...
GeneralRe: multiple sliding window i n one activitymemberSanjay22Tomar18 Apr '13 - 0:53 
hello....
AnswerRe: multiple sliding window i n one activitymembersujeet878818 Apr '13 - 0:54 
hello
GeneralMy vote of 5membermlkhedekar851 Apr '13 - 19:50 
nice ..logic
QuestionChange Background ColormemberM Rizal Hakim20 Mar '13 - 21:25 
Can you help me to change the background color? thank you Smile | :)
QuestionSoundManagermemberRoystonton19 Feb '13 - 13:24 
package theHardestGame.pac; <--- the package has also an error. Frown | :(
 

 
import org.anddev.andengine.audio.sound.Sound;
 

public class SoundManager { <-- this part has an error i dnt know how to resolve it
 
private Sound mGameOverSound;
private Sound mMunchSound ;
private boolean soundEnabled;

public SoundManager () {
AnswerRe: SoundManagermemberSašo Mađarić20 Feb '13 - 5:50 
There may be version's errors. Can you copy me error message? Smile | :)
GeneralRe: SoundManagermemberhaydarhaydar28 Mar '13 - 4:45 
here is the exact error:
 
Implicit super constructor Object() is undefined. Must explicitly invoke another constructor
 
public SoundManager(){ // <-- gives the error here
    mGameOverSound = null;
    mMunchSound = null;
    soundEnabled = false;
}

QuestionIMAGES AND DRAWABLESmemberRoystonton19 Feb '13 - 13:06 
when i download the source code the drawables are not there the icon is only there. Can u send me the full source code of this project? thankyou verymuch
AnswerRe: IMAGES AND DRAWABLESmemberSašo Mađarić20 Feb '13 - 6:00 
Check folder
TheHardestGame.zip\TheHardestGame\TheHardestGame\assets\gfx
 
Big Grin | :-D
QuestionError game stops unexpectedlymemberTanveer Ali 865 Feb '13 - 5:27 
Hi,
 
I am getting following error in logcat upon loading the game :
 
Didn't find class "theHardestGame.pac.GameLogicController" on path: /data/app/theHardestGame.pac-1.apk
AnswerRe: Error game stops unexpectedlymemberSašo Mađarić20 Feb '13 - 6:01 
Check Android and AndEngine versions Smile | :)
QuestionCrashingmembersapramit29 Jan '13 - 22:20 
01-30 18:14:57.696: E/AndroidRuntime(12095): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{theHardestGame.pac/theHardestGame.pac.GameLogicController}: java.lang.ClassNotFoundException: Didn't find class "theHardestGame.pac.GameLogicController" on path:
/data/app/
theHardestGame.pac-1.apk
 

I dont understand, why is it looking for this class the this path /data/app/
AnswerRe: CrashingmemberSašo Mađarić20 Feb '13 - 6:02 
On emulator or real device?
GeneralRe: CrashingmemberMember 998455115 Apr '13 - 5:26 
same error
on emulator
GeneralMy vote of 5memberkaveribc23 Jan '13 - 21:45 
love d site!!! soo soo helpfull!!! Smile | :)
GeneralRe: My vote of 5memberSašo Mađarić20 Feb '13 - 6:02 
tnx Smile | :)
Questionthanksmemberkamalakarreddy114 Jan '13 - 23:43 
at last it is working but i am not able to control the ball...pls..correct it once again for me ..i am a fresher to the gaming world...
QuestionI can't control the Ball in the Simple Android Ball Game?membernguyen tuan van30 Dec '12 - 0:01 
I can't control the Ball in the Simple Android Ball Game?
 
Can You help me?? mr.truong151@gmail.com
 
I set up AndEngine but when play game then i can not control the ball to the finish.
AnswerRe: I can't control the Ball in the Simple Android Ball Game?memberSašo Mađarić28 Feb '13 - 10:43 
Did you try on real devide or emulator?
QuestionMethod chechTouchTime().membernghelam200816 Nov '12 - 18:18 
I don't understand method checkTouchTime().
Can you explain more?
Thank you!
AnswerRe: Method chechTouchTime().memberSašo Mađarić16 Nov '12 - 21:32 
Just to control screen touch (limits how often can u touch screen)
GeneralRe: Method chechTouchTime().membernghelam200817 Nov '12 - 21:42 
Thanks.
I see in your source code method onAreaTouched() for Setting is nothing Frown | :( . I still don't understand method setBlendFunction(). Can you explain for me? My ability English not good. Thank you. Smile | :) Smile | :)
GeneralRe: Method chechTouchTime().memberSašo Mađarić18 Nov '12 - 0:32 
Smile | :) setBlendFunction is andEngine function for seting blend function Big Grin | :-D
QuestionApplication gives fatal signal 11 error in logcatmemberApurva9016 Sep '12 - 20:32 
When i try to run this application via emulator it gives fatal signal 11 (sigsegv) error in logcat and on emulator display a black screen
AnswerRe: Application gives fatal signal 11 error in logcatmemberSašo Mađarić16 Nov '12 - 21:28 
Maybe there is problem with incompatibile SDK version Smile | :)
QuestionUser manual for this gamememberesunilkumare12 Sep '12 - 22:05 
Dear Sašo Mađarić,
 
First of all, i would like to thank you for posting this game source.
 
I am able to compile and run this game on a Android 2.3.3 emulator. Now i am in level-1 screen.
 
Do you have any user manual for this game, so that i can start playing it. Otherwise i have to dig through the program logic to find out this.
 
--
Thanks and Regards,
Sunil
AnswerRe: User manual for this gamememberSašo Mađarić12 Sep '12 - 22:47 
Hi! Tnx for question. In game u have to collect all diamonds (if they are there) and go to finish with ball. Is that answer to your questions? Game logic is finished, but levels are quite bad designed, so it may not be so fun to play it Smile | :)
GeneralRe: User manual for this gamememberesunilkumare12 Sep '12 - 23:23 
Hi,
 
Thanks for your reply.
 
I can see a ball going upwards & downwards. But on emualtor clicking, dragging on screen using mouse doesn't have any impact.
 
Thats why i asked this question. I have to move the moving ball across the screen to collect the objects. Am i right ?
 
--
Sunil
GeneralRe: User manual for this gamememberSašo Mađarić12 Sep '12 - 23:25 
Ah, i see where is problem Smile | :) Game is using accelometer, so you should test in on phone... Yes you have to move the ball across the screen to collect the objects. Smile | :)
GeneralRe: User manual for this gamememberesunilkumare12 Sep '12 - 23:41 
Ohhh my bad Smile | :)
 
Thanks for your help. I will try it on actual phone.
 
--
Sunil
GeneralRe: informationmemberhemraj roy1 Mar '13 - 22:37 
i want to know which place i use this gamecode for design my game could some one explain me how it is work.
i am too dummy in programming of game.
GeneralRe: informationmemberSašo Mađarić2 Mar '13 - 5:08 
Hmm you want to make your own game without any knowledge about programming? Smile | :)
QuestionerrormemberBhartendu verma28 Aug '12 - 6:13 
when i import the project from workspace then it shows error unable to resolve target android 4
AnswerRe: errormemberSašo Mađarić30 Aug '12 - 6:15 
You need to have android 4 SDK.
QuestionApplication is crashing with error (process Hardestgame.pac stop unexpectedly)memberGuptaSaurabh2k96 Aug '12 - 8:14 
When i am trying to run the application via emulator or phone its giving me error with message that (process Hardestgame.pac stop unexpectedly)
Could you please let me know why it is and what is the solution.
I didn't make any change in the given code.
 
Thanks!
AnswerRe: Application is crashing with error (process Hardestgame.pac stop unexpectedly)memberSašo Mađarić30 Aug '12 - 6:15 
Probably there is version problem.
AnswerRe: Application is crashing with error (process Hardestgame.pac stop unexpectedly)memberesunilkumare12 Sep '12 - 22:01 
you need to add the 'libs' folder to the build-path and check all the jars & libs folder in 'Order and export 'tab. Then this error will go
QuestionApp crashes at launchmemberMember 869768716 May '12 - 5:10 
Hello there. Thanks for the great tutorial. I tried to run the code from your sources but the app craches at launch with no usefull informations in LogCat.
Is there any chance that you could take a look at your (old) code regarding the GLES2 compatibility?
 
Regards
GeneralMy vote of 5memberRajender Bhambhu4 Apr '12 - 22:19 
Nicely explained
QuestionFails with latest AndEngine JarsmemberzQz10 Aug '11 - 7:01 
I am new at android programming. Thank you for this example.
 
I put the latest AndEngine Jars in the project and now it is giving multiple errors on the EnemyManager, GameLogicController, and LevelController classes.
 
Can someone please help with the fixes? It looks like the AE library defs have changed causing compile errors.
 
Thank You.
QuestionA problem while using PhysicsWorldmembernemax721 Jul '11 - 15:53 
I write a small code with andEngine & I get in trouble with using the class PyisicsWord,once I add the physicsworld to the scene,the app will crash,can you help me with this problem?
AnswerRe: A problem while using PhysicsWorldmemberSašo Mađarić21 Jul '11 - 21:25 
Yes shure. Can i see your source code?
GeneralRe: A problem while using PhysicsWorldmembernemax722 Jul '11 - 2:04 
I finally find the reason why it crashed once I create a physical world,because I forget to add those so format file to my project.And now my code works well,but it doesn`t complete.I`m trying to write a ballance ball game using andEngine,so I read your source code for conference.It`s really help me a lot,thanks. Laugh | :laugh:
 
I don`t konw if I can post my code in this message,but I`ll upload it to my server,you can download it for fun,it`s short and it`s based on old version andEngine libraries;
 
My source code:
http://www.andtwo.tk/test/[^]
 
Thanks for your attention!
GeneralRe: A problem while using PhysicsWorldmemberSašo Mađarić22 Jul '11 - 22:17 
Hehe Big Grin | :-D No problem Big Grin | :-D
QuestionthanksmemberAlucard_desu3 Jul '11 - 6:55 
Great work! Very laconic solution for this result.
Questionfew questions....membertnautanki17 May '11 - 21:34 
hello.....
i am intrested in making an andrioid based game....
.
i want to no that this coding thing for example this
 
@Override
public void onAccelerometerChanged(AccelerometerData pAccelerometerData) {
this.mGravityX = pAccelerometerData.getY() * 2;
this.mGravityY = pAccelerometerData.getX() * 2;
if(this.mGravityX > con)
this.mGravityX = con;
if(this.mGravityY > con)
this.mGravityY = con;
if(this.mGravityX < con * (-1))
this.mGravityX = con * (-1);
if(this.mGravityY < con * (-1))
this.mGravityY = con * (-1);
this.mTempVector.set(this.mGravityX, this.mGravityY);
this.mPhysicsWorld.setGravity(this.mTempVector);
}"
 
am i supposed to do this....
i mean i simply have no idea whats going on in these lines,
what language is it,how do i learn it and will i b able to make a game by just learning this languag.....
plzzz reply me....
AnswerRe: few questions....memberSašo Mađarić17 May '11 - 23:00 
Hello
 
This method is already implemented in andEngine(it's overrided method). I just changed behavior of method with adding some lines. Programming language is Java.
 
pAccelerometerData.getY() //Read "Y data" from Accelometer (sensor in mobile phone)
With multiplication (*2) i just made sensor data more sensitive (ball will be faster in game)
 
same story with "X data".
 
Let's explain next lines... Idea is to limit ball speed. Ball shouldn't be too fast. So we just calculate new ball speed
and if it is too fast we need to decrase ball speed. Ball speed can be represented as moving to X/Y direction... so can be
positive or negative(ball can move to all ways (360 degrees).
 
if(this.mGravityX > con)
this.mGravityX = con;
if(this.mGravityY > con)
this.mGravityY = con;
if(this.mGravityX < con * (-1))
this.mGravityX = con * (-1);
if(this.mGravityY < con * (-1))
this.mGravityY = con * (-1);
 
With those two lines, we just update new ball speed.
this.mTempVector.set(this.mGravityX, this.mGravityY);
this.mPhysicsWorld.setGravity(this.mTempVector);

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 29 Apr 2011
Article Copyright 2011 by Sašo Mađarić
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid