Archive for the ‘Android Game Programming’ Category

Android Game using AndEngine- Part-1

January 12th, 2012 by aabhaanjan

We will learn how to develop a game using AndEngine which is a openSource, free game engine 🙂 for android.
Step :1. Download the AndEngine from here :

AndEngine.jar

Step :2. Create a new project using motodev.
andEngine
Step :3. Create a new folder ‘lib’ and paste AndEngine.jar file there.
lib_folder

Paste the AndEngine.jar file
inside_lib_folder

Step :4. Go to project properyies and add AndEngine.jar file in the build path.
java build path

Step :5. Open MainActivity.java file and extend it to the BaseActivity

Step :6 You will get an error thrown. Now import the default methods of AndEngine.
extend to the base activity of AndEnine
Step :7. Your Main activity will look like this. These four are the default method of AndEngine

a)onLoadEngine()
a)onLoadResources()
a)onLoadScene()
a)onLoadComplete()

[xml]
package com.andenginedemo;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.ui.activity.BaseGameActivity;

public class MainActivity extends BaseGameActivity {

@Override
public Engine onLoadEngine() {
// TODO Auto-generated method stub
return null;
}

@Override
public void onLoadResources() {
// TODO Auto-generated method stub

}

@Override
public Scene onLoadScene() {
// TODO Auto-generated method stub
return null;
}

@Override
public void onLoadComplete() {
// TODO Auto-generated method stub

}
/** Called when the activity is first created. */

}
[/xml]

Step :7. Open the assets folder and create a folder gfx and put the ball.png file there.

Step :8. Now put following code in your MainActivity.java class

[xml]
package com.andenginedemo;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;

import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;

public class MainActivity extends BaseGameActivity {

private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;

private Camera _refCamera;
private Texture _ballBitmapTexture;
private TextureRegion _ballTextureRegion;

@Override
public Engine onLoadEngine() {
this._refCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this._refCamera));
}

@Override
public void onLoadResources() {
this._ballBitmapTexture = new Texture(256,256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this._ballTextureRegion= TextureRegionFactory.createFromAsset(this._ballBitmapTexture, this, “gfx/ball.png”, 0, 0); // 64×32
this.mEngine.getTextureManager().loadTexture(this._ballBitmapTexture);
}

@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
Scene scene = new Scene(2);
scene.setBackground(new ColorBackground(0.0000f, 0.0000f, 0.0000f));
/* Calculate the coordinates for the face, so its centered on the camera. */
final int centerX = (CAMERA_WIDTH – this._ballTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT – this._ballTextureRegion.getHeight()) / 2;

/* Create the face and add it to the scene. */
final Sprite face = new Sprite(centerX, centerY, this._ballTextureRegion);
scene.getTopLayer().addEntity(face);
return scene;
}

@Override
public void onLoadComplete() {

}

}
[/xml]

Step :9. Run your app it will look like this. Enjoy 🙂
final
Get AndEngineDemo source Code

Box2D Game demo in Android

January 10th, 2012 by aabhaanjan

Lets see in this tutorial we will learn how to develop an android game with Box2d. There are following steps :

Step :1. Create a project using motodev.
1

Step :2. Create a lib folder inside the project and put jbox2d-2.0.1-full.jar file there.
lib_folder
Step :3. Open the project properties and add the jar file in the library.
import_Jbox
Step :4. Rename the MainActivity.java into Box2dGame.java put the same in AndroidManifest.xml. Now open the class and put following code

[xml]
package com.physicssample;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;

public class Box2dGame extends Activity
{
private GLSurfaceView _surfaceView;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
_surfaceView = new ClearGLSurfaceView(this);
setContentView(_surfaceView);
}

@Override
protected void onPause() {
super.onPause();
_surfaceView.onPause();
}

@Override
protected void onResume() {
super.onResume();
_surfaceView.onResume();
}

}

[/xml]

Step :5. Now create a ClearGLSurfaceView.java class and put following code inside the class

[xml]
package com.physicssample;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;

public class ClearGLSurfaceView extends GLSurfaceView
{
ClearRenderer _refRenderer;
public ClearGLSurfaceView(Context context) {
super(context);
_refRenderer = new ClearRenderer(context);
setRenderer(_refRenderer);
}

public boolean onTouchEvent(final MotionEvent event) {
_refRenderer.setSize(this.getWidth(),this.getHeight());
queueEvent(new Runnable(){
public void run() {
_refRenderer.touchEvent(event.getX(), event.getY(), event.getAction());
}});
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
}
[/xml]

Step :5. Now create a ClearRenderer.java class and put following code inside the class

[xml]
package com.physicssample;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import org.jbox2d.collision.PolygonShape;
import org.jbox2d.collision.Shape;
import org.jbox2d.collision.ShapeType;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.view.MotionEvent;

public class ClearRenderer implements GLSurfaceView.Renderer
{
private PhysicsWorld _physicsWorld;
private ObjectCreater _refBox;
private Context _context;
private int _width;
private int _height;

public ClearRenderer(Context newContext)
{
_context = newContext;
_refBox = new ObjectCreater(new float[]{-1,-1,0,1,-1,0,1,1,0,-1,1,0}, new float[]{ 0f,1f, 1f,1f, 1f,0f,0f,0f},new short[]{0,1,2,3,0},5);
_physicsWorld = new PhysicsWorld();
_physicsWorld.createWorld();
_physicsWorld.addBox(0f, -25f, 50f, 10f, 0f, false);
}

public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
GLU.gluOrtho2D(gl, -12f, 12f, -20f, 20f);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_REPEAT);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_REPEAT);
_refBox.loadTexture(gl, _context, R.drawable.box);
}

public void onSurfaceChanged(GL10 gl, int w, int h)
{
gl.glViewport(0, 0, w, h);
}

public void onDrawFrame(GL10 gl)
{
gl.glClearColor(0f, 0, 0.5f, 1.0f);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_REPLACE);
gl.glColor4f(1f, 1f, 1f, 1f);
Vec2 vec;
Body _body = _physicsWorld.getBodyList();
do
{
Shape _shape = _body.getShapeList();
if (_shape != null)
{
vec = _body.getPosition();
float rot = _body.getAngle() * 57f;
if (ShapeType.POLYGON_SHAPE == _shape.getType())
{
Vec2[] _vertexes = ((PolygonShape)_shape).getVertices();
_refBox.draw(gl, vec.x, vec.y, 0f, rot, _vertexes[2].x, _vertexes[2].y);
}

}
_body = _body.getNext();
}
while (_body != null);
_physicsWorld.update();
}

public void touchEvent(float x, float y, int eventCode)
{
float _worldX = ((x-(this._width/2))*12f)/(this._width/2);
float _worldY = ((y-(this._height/2))*-20f)/(this._height/2);
if (eventCode == MotionEvent.ACTION_UP)
{
_physicsWorld.addBox(_worldX, _worldY, .98f, .98f, 0f, true);

}
}

public void setSize(int x, int y)
{
this._width = x;
this._height = y;
}
}

[/xml]

Step :6. Now create a PhysicsWorld.java class and put following code inside the class

[xml]
package com.physicssample;
import org.jbox2d.collision.AABB;
import org.jbox2d.collision.PolygonDef;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.World;

public class PhysicsWorld
{
final private int MAXBOX = 20;
final private float FRAMERATE = 30f;
private float _timeStep = (1f / FRAMERATE);
private int _iterations = 5;
private int _count = 0;

private AABB _box2dWorld;
private World _myWorld;

public void createWorld()
{
_box2dWorld = new AABB();
_box2dWorld.lowerBound.set(new Vec2(-100f, -100f));
_box2dWorld.upperBound.set(new Vec2(100f, 100f));

Vec2 gravity = new Vec2(0f, -10f);
boolean doSleep = false;
_myWorld = new World(_box2dWorld, gravity, doSleep);

}

public void setGrav(float x, float y)
{
_myWorld.setGravity(new Vec2(x,y));
}

public void addBox(float x, float y, float xr, float yr, float angle, boolean dynamic)
{
if (_count < (MAXBOX-1)) { BodyDef _groundBody; _groundBody = new BodyDef(); _groundBody.position.set(new Vec2(x, y)); _groundBody.angle = angle; Body groundBody = _myWorld.createBody(_groundBody); PolygonDef _groundShape; _groundShape = new PolygonDef(); _groundShape.setAsBox(xr, yr); _groundShape.density = 1.0f; groundBody.createShape(_groundShape); if (dynamic) { groundBody.setMassFromShapes(); } if (dynamic) { _count++; } } } public void update() { _myWorld.step(_timeStep, _iterations); } public int getCount() { return _count; } public Body getBodyList() { return _myWorld.getBodyList(); } } [/xml] Step :6. Now create a ObjectCreater.java class and put following code inside the class [xml] package com.physicssample; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLUtils; public class ObjectCreater { private FloatBuffer _vertexBuffer; private ShortBuffer _indexBuffer; private FloatBuffer _texBuffer; private int _vertexCount = 0; private boolean _hasTexture = false; private int[] _texture = new int[1]; public ObjectCreater(float[] coords, float[] tcoords, short[] icoords, int vertexes) { this(coords, icoords, vertexes); _texBuffer = makeFloatBuffer(tcoords); } public ObjectCreater(float[] coords, short[] icoords, int vertexes) { _vertexCount = vertexes; _vertexBuffer = makeFloatBuffer(coords); _indexBuffer = makeShortBuffer(icoords); } protected static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length*4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } protected static ShortBuffer makeShortBuffer(short[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length*4); bb.order(ByteOrder.nativeOrder()); ShortBuffer ib = bb.asShortBuffer(); ib.put(arr); ib.position(0); return ib; } public void loadTexture(GL10 gl, Context mContext, int mTex) { _hasTexture = true; gl.glGenTextures(1, _texture, 0); gl.glBindTexture(GL10.GL_TEXTURE_2D, _texture[0]); Bitmap bitmap; bitmap = BitmapFactory.decodeResource(mContext.getResources(), mTex); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR ); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR ); } public void draw(GL10 gl) { if (_hasTexture) { gl.glEnable(GL10.GL_TEXTURE_2D); gl.glBindTexture(GL10.GL_TEXTURE_2D, _texture[0]); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, _texBuffer); } else { gl.glDisable(GL10.GL_TEXTURE_2D); } gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, _vertexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_FAN, _vertexCount, GL10.GL_UNSIGNED_SHORT, _indexBuffer); gl.glDisable(GL10.GL_TEXTURE_2D); } public void draw(GL10 gl, float x, float y, float z, float rot, float scale) { this.draw(gl, x, y, z, rot, scale, scale); } public void draw(GL10 gl, float x, float y, float z, float rot, float scaleX, float scaleY) { gl.glPushMatrix(); gl.glTranslatef(x, y, z); gl.glRotatef(rot, 0f, 0f, 1f); gl.glScalef(scaleX, scaleY, 1f); this.draw(gl); gl.glPopMatrix(); } } [/xml] Step :6. Run your app it will look like this . If you have any question or need more clarification please write on forum.dremsus.com. final

Handle Collision detection with Sprites

January 6th, 2012 by aabhaanjan

In this article we are going to learn how to add multiple sprits and handle their Collision. Lets start with following steps :

Step 1: Create a new MotoDev project.
MultipleSprite_Android

Step 2: Create sprite sheet animation for three character’s walk cycle.

boy1

Step 3: Put them in res/drawable folder.

Step 4: Open MainActivity.java class and add following code :
[xml]
package com.multiplesp;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new GameController(this));

}

}
[/xml]

Step 5: Create a new class GameController.java and put following code inside it
[xml]
package com.multiplesp;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;

public class GameController extends SurfaceView {

private SurfaceHolder _surfaceHolder;
private GameThread _gameThread;
private List Character = new ArrayList();
private long lastClick;
public GameController(Context context) {

super(context);
_gameThread = new GameThread(this);
_surfaceHolder = getHolder();
_surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder _surfaceHolder) {
boolean retry = true;
_gameThread.setRunning(false);
while (retry) {
try {
_gameThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
@Override
public void surfaceCreated(SurfaceHolder _surfaceHolder) {
createSprites();
_gameThread.setRunning(true);
_gameThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder _surfaceHolder, int format,
int width, int height) {
}
});
}

private void createSprites() {
Character.add(createSprite(R.drawable.boy1));
Character.add(createSprite(R.drawable.girl1));
Character.add(createSprite(R.drawable.girl2));

}

private Character createSprite(int resouce) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
return new Character(this,bmp);
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
for (Character sprite : Character) {
sprite.onDraw(canvas);
}
}
@Override

public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() – lastClick > 500) {
lastClick = System.currentTimeMillis();
synchronized (getHolder()) {
for (int i = Character.size() – 1; i >= 0; i–) {
Character character = Character.get(i);
if (character.isCollition(event.getX(), event.getY())) {
Character.remove(character);
break;
}
}
}
}

return true;
}

}

[/xml]

Step 7: Create a GameThread Class and put following code inside :
[xml]
package com.multiplesp;

import android.graphics.Canvas;

public class GameThread extends Thread {
private GameController _gameController;
private boolean _isRunning = false;
static final long FPS = 10;

public GameThread(GameController _gameController) {
this._gameController = _gameController;
}

public void setRunning(boolean run) {
_isRunning = run;
}

@Override

public void run() {
long _trackFPS = 1000 / FPS;
long _startCounter;
long _sleepTime;
while (_isRunning) {
Canvas _canvas = null;
_startCounter = System.currentTimeMillis();
try {
_canvas = _gameController.getHolder().lockCanvas();
synchronized (_gameController.getHolder()) {
_gameController.onDraw(_canvas);
}

} finally {
if (_canvas != null) {
_gameController.getHolder().unlockCanvasAndPost(_canvas);
}
}
_sleepTime = _trackFPS – (System.currentTimeMillis() – _startCounter);
try {
if (_sleepTime > 0)
sleep(_sleepTime);
else
sleep(10);
} catch (Exception e) {}

}

}

}
[/xml]

Step 8:Create a Character.java class for your sprites. Put following code inside that:
[xml]
package com.multiplesp;

import java.util.Random;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

public class Character {
int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 };
private static final int CHAR_ROWS = 4;
private static final int CHAR_COLUMNS = 3;
private static final int MAX_SPEED = 5;
private GameController GameController;
private Bitmap _characterbmp;
private int _xPos = 0;
private int _yPos = 0;
private int _xVelocity;
private int _yVelocity;
private int _currentFrame = 0;
private int _width;
private int _height;

public Character(GameController GameController, Bitmap _characterbmp) {
this._width = _characterbmp.getWidth() / CHAR_COLUMNS;
this._height = _characterbmp.getHeight() / CHAR_ROWS;
this.GameController = GameController;
this._characterbmp = _characterbmp;
Random _randomValue = new Random();
_xPos = _randomValue.nextInt(GameController.getWidth() – _width);
_yPos = _randomValue.nextInt(GameController.getHeight() – _height);
_xVelocity = _randomValue.nextInt(MAX_SPEED * 2) – MAX_SPEED;
_yVelocity = _randomValue.nextInt(MAX_SPEED * 2) – MAX_SPEED;
}

private void update() {
if (_xPos >= GameController.getWidth() – _width – _xVelocity || _xPos + _xVelocity <= 0) { _xVelocity = -_xVelocity; } _xPos = _xPos + _xVelocity; if (_yPos >= GameController.getHeight() – _height – _yVelocity || _yPos + _yVelocity <= 0) { _yVelocity = -_yVelocity; } _yPos = _yPos + _yVelocity; _currentFrame = ++_currentFrame % CHAR_COLUMNS; } public void onDraw(Canvas canvas) { update(); int orgX = _currentFrame * _width; int orgY = getAnimationRow() * _height; Rect src = new Rect(orgX, orgY, orgX + _width, orgY + _height); Rect dst = new Rect(_xPos, _yPos, _xPos + _width, _yPos + _height); canvas.drawBitmap(_characterbmp, src, dst, null); } private int getAnimationRow() { double dirDouble = (Math.atan2(_xVelocity, _yVelocity) / (Math.PI / 2) + 2); int direction = (int) Math.round(dirDouble) % CHAR_ROWS; return DIRECTION_TO_ANIMATION_MAP[direction]; } public boolean isCollition(float x2, float y2) { return x2 > _xPos && x2 < _xPos + _width && y2 > _yPos && y2 < _yPos + _height; } } [/xml] Step 9: Run your application . It should look like this : final

Handle Multiple Character and their Movement

January 5th, 2012 by aabhaanjan

In this article we are going to learn how to add multiple sprits and handle their movement. Lets start with following steps :

Step 1: Create a new MotoDev project.
MultipleSprite_Android

Step 2: Create sprite sheet animation for three character’s walk cycle.

boy1

Step 3: Put them in res/drawable folder.

Step 4: Open MainActivity.java class and add following code :
[xml]
package com.multiplesp;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new GameController(this));

}

}
[/xml]

Step 5: Create a new class GameController.java and put following code inside it
[xml]

package com.multiplesp;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;

public class GameController extends SurfaceView {

private SurfaceHolder _surfaceHolder;
private GameThread _gameThread;
private List Character = new ArrayList();
public GameController(Context context) {

super(context);
_gameThread = new GameThread(this);
_surfaceHolder = getHolder();
_surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder _surfaceHolder) {
boolean retry = true;
_gameThread.setRunning(false);
while (retry) {
try {
_gameThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
@Override
public void surfaceCreated(SurfaceHolder _surfaceHolder) {
createSprites();
_gameThread.setRunning(true);
_gameThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder _surfaceHolder, int format,
int width, int height) {
}
});
}

private void createSprites() {
Character.add(createSprite(R.drawable.boy1));
Character.add(createSprite(R.drawable.girl1));
Character.add(createSprite(R.drawable.girl2));

}

private Character createSprite(int resouce) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
return new Character(this,bmp);
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
for (Character sprite : Character) {
sprite.onDraw(canvas);
}
}

}

[/xml]

Step 7: Create a GameThread Class and put following code inside :
[xml]
package com.multiplesp;

import android.graphics.Canvas;

public class GameThread extends Thread {
private GameController _gameController;
private boolean _isRunning = false;

public GameThread(GameController _gameController) {
this._gameController = _gameController;
}

public void setRunning(boolean run) {
_isRunning = run;
}

@Override
public void run() {
while (_isRunning) {
Canvas _canvas = null;
try {
_canvas = _gameController.getHolder().lockCanvas();
synchronized (_gameController.getHolder()) {
_gameController.onDraw(_canvas);
}

} finally {
if (_canvas != null) {
_gameController.getHolder().unlockCanvasAndPost(_canvas);
}
}
}
}

}
[/xml]

Step 8:Create a Character.java class for your sprites. Put following code inside that:
[xml]
package com.multiplesp;

import java.util.Random;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

public class Character {
int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 };
private static final int CHAR_ROWS = 4;
private static final int CHAR_COLUMNS = 3;
private static final int MAX_SPEED = 5;
private GameController GameController;
private Bitmap _characterbmp;
private int _xPos = 0;
private int _yPos = 0;
private int _xVelocity;
private int _yVelocity;
private int _currentFrame = 0;
private int _width;
private int _height;

public Character(GameController GameController, Bitmap _characterbmp) {
this._width = _characterbmp.getWidth() / CHAR_COLUMNS;
this._height = _characterbmp.getHeight() / CHAR_ROWS;
this.GameController = GameController;
this._characterbmp = _characterbmp;
Random _randomValue = new Random();
_xPos = _randomValue.nextInt(GameController.getWidth() – _width);
_yPos = _randomValue.nextInt(GameController.getHeight() – _height);
_xVelocity = _randomValue.nextInt(MAX_SPEED * 2) – MAX_SPEED;
_yVelocity = _randomValue.nextInt(MAX_SPEED * 2) – MAX_SPEED;
}

private void update() {
if (_xPos >= GameController.getWidth() – _width – _xVelocity || _xPos + _xVelocity <= 0) { _xVelocity = -_xVelocity; } _xPos = _xPos + _xVelocity; if (_yPos >= GameController.getHeight() – _height – _yVelocity || _yPos + _yVelocity <= 0) { _yVelocity = -_yVelocity; } _yPos = _yPos + _yVelocity; _currentFrame = ++_currentFrame % CHAR_COLUMNS; } public void onDraw(Canvas canvas) { update(); int orgX = _currentFrame * _width; int orgY = getAnimationRow() * _height; Rect src = new Rect(orgX, orgY, orgX + _width, orgY + _height); Rect dst = new Rect(_xPos, _yPos, _xPos + _width, _yPos + _height); canvas.drawBitmap(_characterbmp, src, dst, null); } private int getAnimationRow() { double dirDouble = (Math.atan2(_xVelocity, _yVelocity) / (Math.PI / 2) + 2); int direction = (int) Math.round(dirDouble) % CHAR_ROWS; return DIRECTION_TO_ANIMATION_MAP[direction]; } } [/xml] Step 9: Run your application . It should look like this : output

Coordinate Movement for a Ball

January 2nd, 2012 by aabhaanjan

Step 1 : Create a new project using Motodev Studio.
1
Step 2: Put an image of ball named “ball_1.png” into res/drwable Folder.

Step 3: Open you MainActivity.java and put following code :

[xml]
package com.movement;

import android.app.Activity;

import android.os.Bundle;

import android.view.Window;

public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new GameController(this));

}

@Override

protected void onDestroy() {
super.onDestroy();

}

@Override

protected void onStop() {
super.onStop();

}

}

[/xml]

Step 3: Create a class Ball.java and put following code :

[xml]

package com.movement;

import android.graphics.Bitmap;

import android.graphics.Canvas;

public class Ball {

private Bitmap bitmap;

private int x;
private int y;
private SpeedManager speed;

public Ball(Bitmap bitmap, int x, int y) {

this.bitmap = bitmap;

this.x = x;

this.y = y;

this.speed = new SpeedManager();

}

public Bitmap getBitmap() {

return bitmap;

}

public void setBitmap(Bitmap bitmap) {

this.bitmap = bitmap;

}

public int getX() {

return x;

}

public void setX(int x) {

this.x = x;

}

public SpeedManager getSpeed() {

return speed;

}

public void setSpeed(SpeedManager speed) {

this.speed = speed;

}

public void draw(Canvas canvas) {

canvas.drawBitmap(bitmap, x – (bitmap.getWidth() / 2), y – (bitmap.getHeight() / 2), null);

}

public void update() {

x += (speed.getvelocity() * speed.getxDirection());
}

}

[/xml]
Step 4: Create a class GameController.java and put following code :
[xml]
package com.movement;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameController extends SurfaceView implements
SurfaceHolder.Callback {
private GameThread thread;
private Ball ballInstance;

public GameController(Context context) {
super(context);
getHolder().addCallback(this);
ballInstance = new Ball(BitmapFactory.decodeResource(getResources(), R.drawable.ball_1), 80, 80);
thread = new GameThread(getHolder(), this);
setFocusable(true);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {

}
}

}

public void render(Canvas canvas) {
canvas.drawColor(Color.BLACK);
ballInstance.draw(canvas);
}

public void update() {
if (ballInstance.getSpeed().getxDirection() == SpeedManager.DIRECTION_RIGHT
&& ballInstance.getX() + ballInstance.getBitmap().getWidth() / 2 >= getWidth()) {
ballInstance.getSpeed().toggleXDirection();
}

if (ballInstance.getSpeed().getxDirection() == SpeedManager.DIRECTION_LEFT
&& ballInstance.getX() – ballInstance.getBitmap().getWidth() / 2 <= 0) { ballInstance.getSpeed().toggleXDirection(); } ballInstance.update(); } } [/xml] Step 5: Create a thread GameThread.java and put following code : [xml] package com.movement; import android.graphics.Canvas; import android.view.SurfaceHolder; public class GameThread extends Thread { private SurfaceHolder surfaceHolder; private GameController gameController; private boolean running; public void setRunning(boolean running) { this.running = running; } public GameThread(SurfaceHolder surfaceHolder, GameController gameController) { super(); this.surfaceHolder = surfaceHolder; this.gameController = gameController; } @Override public void run() { Canvas canvas; while (running) { canvas = null; try { canvas = this.surfaceHolder.lockCanvas(); synchronized (surfaceHolder) { this.gameController.update(); this.gameController.render(canvas); } } finally { if (canvas != null) { surfaceHolder.unlockCanvasAndPost(canvas); } } } } } [/xml] Step 6: Create a thread SpeedManager.java and put following code : [xml] package com.movement; public class SpeedManager { public static final int DIRECTION_RIGHT = 1; public static final int DIRECTION_LEFT = -1; private float velocity = 10; private int xDirection = DIRECTION_RIGHT; public SpeedManager() { this.velocity = 1; } public SpeedManager(float velocity, float yv) { this.velocity = velocity; } public float getvelocity() { return velocity; } public void setvelocity(float velocity) { this.velocity = velocity; } public int getxDirection() { return xDirection; } public void setxDirection(int xDirection) { this.xDirection = xDirection; } public void toggleXDirection() { xDirection = xDirection * -1; } } [/xml] Step 7:Run your application It will look like this : 2

Blinking Santa Handling alpha feature

December 16th, 2011 by aabhaanjan

In this article we are going to learn how to make an blinking image on touch or click.
There are following steps we need to follow to make Blinking Santa.

Step 1: Create a Project using Motodev. The options will look like this.
1

Step 2: in your res/drwable folder put the image santa.png

Step 3. Open the layout/Main.xml and put following codes

[xml]


[/xml]

Step 4. Open the MainActivity.java and put following codes
[xml]

package com.blinkingsanta;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.animation.Animation;

import android.view.animation.Animation.AnimationListener;

import android.widget.ImageView;

public class MainActivity extends Activity implements OnClickListener, AnimationListener {

private ImageView _santaImage;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

_santaImage = (ImageView) findViewById(R.id.image);

_santaImage.setOnClickListener(this);

}

@Override

public void onClick(View view) {

if (view.getId() == R.id.image) {

Animation animation;

if (_santaImage.getVisibility() == View.VISIBLE) {

animation = new VisibilityClass(3, true);
}

else
{

animation = new VisibilityClass(3, false);

}

animation.setDuration(1000L);

animation.setAnimationListener(this);
_santaImage.startAnimation(animation);

}

}

@Override

public void onAnimationEnd(Animation animation) {

_santaImage.setVisibility(View.VISIBLE);

}

@Override

public void onAnimationRepeat(Animation animation) {

}

@Override

public void onAnimationStart(Animation animation) {

}

}

[/xml]

Step 5. Create a new class VisibilityClass.java and put following codes

[xml]

package com.blinkingsanta;

import android.util.FloatMath;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class VisibilityClass extends Animation {
private int _totalNumber;
private boolean _isAnimFinished;

public VisibilityClass(int _totalNumber, boolean _isAnimFinished) {
this._totalNumber = _totalNumber;
this._isAnimFinished = _isAnimFinished;
}

@Override
protected void applyTransformation(float _interpolatedTime, Transformation _trans) {
float period = _interpolatedTime * _totalNumber * 4.12f + (_isAnimFinished ? 4.12f / 2 : 0);
_trans.setAlpha(Math.abs(FloatMath.cos(period)));
}

}

[/xml]

Step 6. Run the app and Click on Santa . It should look like this 🙂

2

Tags: , , , , , , , , , , , , ,

Handling animation in Android Game Programming

December 13th, 2011 by aabhaanjan

In this article we are going to learn how to handle the animations for a game in Android programming.
We are going to show an animation of duck and its creation on touch event. So lets begin it wih steps :

Step :1 Create a motodev Project .
1

Step :2 Now put your animation sprite(png) file into res/drawable folder.Your png will look like this
duck

Step :3 Open your Layout/Main.xml file and put following code there :

[xml]


[/xml]

Step :4 Open your values/String.xml and put following code inside that

[xml]


AnimatedDuck

[/xml]

Step :5 Your MainActivity class will look like this :
[xml]

package com.annimatedspriteapp;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

}

}
[/xml]

Step :6 Now create a Class for the Sprite . Here I am creating the class named ‘DuckSprite’.
and adding following codes :

[xml]

package com.annimatedspriteapp;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

public class DuckSprite {
private Bitmap _duckAnim;
private int _xPos;
private int _yPos;
private Rect _duckRect;
private int _fps;
private int _frameCount;
private int _currentFrame;
private long _frameTimer;
private int _duckHeight;
private int _duckWidth;
private boolean _loop;
public boolean dispose;

public DuckSprite() {
_duckRect = new Rect(0, 0, 0, 0);
_frameTimer = 0;
_currentFrame = 0;
_xPos = 80;
_yPos = 200;
dispose = false;
}

public void Initialize(Bitmap __bitmap, int __height, int __width, int __fps, int __frameCount, boolean __loop) {
this._duckAnim = __bitmap;
this._duckHeight = __height;
this._duckWidth = __width;
this._duckRect.top = 0;
this._duckRect.bottom = _duckHeight;
this._duckRect.left = 0;
this._duckRect.right = _duckWidth;
this._fps = 1000 / __fps;
this._frameCount = __frameCount;
this._loop = __loop;
}

public int getXPos() {
return _xPos;
}

public int getYPos() {
return _yPos;
}

public void setXPos(int value) {
_xPos = value – (_duckWidth/2);
}

public void setYPos(int value) {
_yPos = value – (_duckHeight/2);
}

public void Update(long _totalTime) {
if( _totalTime > _frameTimer + _fps) {
_frameTimer = _totalTime;
_currentFrame += 1;

if( _currentFrame >= _frameCount ) {
_currentFrame = 0;

if(!_loop)
dispose = true;

}

_duckRect.left = _currentFrame * _duckWidth;
_duckRect.right = _duckRect.left + _duckWidth;
}
}

public void draw(Canvas canvas) {
Rect dest = new Rect(getXPos(), getYPos(), getXPos() + _duckWidth,
getYPos() + _duckHeight);
canvas.drawBitmap(_duckAnim, _duckRect, dest, null);
}
}

[/xml]

Step :7 Now I am going to create the View Class. Here I named it DuckView

[xml]

package com.annimatedspriteapp;

import java.util.ArrayList;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Handler;

import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

class DuckView extends SurfaceView implements SurfaceHolder.Callback {
class AnimationThread extends Thread {
private Bitmap _duck;
private ArrayList _mSpritesArray;
private ArrayList _mSpritesArraytoRemove;

private boolean _isRunning = false;
private SurfaceHolder _mSurfaceHolder;
private Resources _res;

public AnimationThread(SurfaceHolder surfaceHolder, Context context, Handler handler) {

_mSurfaceHolder = surfaceHolder;
_res = context.getResources();
_mSpritesArray = new ArrayList();
_mSpritesArraytoRemove = new ArrayList();

}

@Override
public void run() {
while (_isRunning) {
Canvas _mcanvas = null;
try {
_mcanvas = _mSurfaceHolder.lockCanvas(null);
synchronized (_mSurfaceHolder) {
updateAnimation();
doDraw(_mcanvas);
}
} catch(Exception e){

}finally {

if (_mcanvas != null) {
_mSurfaceHolder.unlockCanvasAndPost(_mcanvas);
}
}
}
}

private void doDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
for( DuckSprite _anDuck : _mSpritesArray){
_anDuck.draw(canvas);
}
canvas.restore();
}

private void updateAnimation() {
long _currentTime = System.currentTimeMillis();
synchronized(_mSpritesArray){
for( DuckSprite _anDuck : _mSpritesArray){
_anDuck.Update(_currentTime);
if(_anDuck.dispose)
_mSpritesArraytoRemove.add(_anDuck);
}
}

synchronized(_mSpritesArraytoRemove){
_mSpritesArray.removeAll(_mSpritesArraytoRemove);
_mSpritesArraytoRemove.clear();
}

}

public void doTouch(MotionEvent event){
int action = event.getAction();
float x = event.getX();
float y = event.getY();
switch(action){
case MotionEvent.ACTION_DOWN:
DuckSprite _anDuck = new DuckSprite();
if(_duck == null)
_duck = BitmapFactory.decodeStream(_res.openRawResource(R.drawable.duck));
_anDuck.Initialize(_duck, 100, 100, 35,28, true);
_anDuck.setXPos((int)x);
_anDuck.setYPos((int)y);
synchronized(_mSpritesArray){
_mSpritesArray.add(_anDuck);
}
break;
}
}

public void setRunning(boolean _flag) {
_isRunning = _flag;
}

public void setSurfaceSize(int width, int height) {
synchronized (_mSurfaceHolder) {
}
}

}

private AnimationThread thread;

public DuckView(Context context, AttributeSet attrs) {
super(context, attrs);
SurfaceHolder holder = getHolder();
holder.addCallback(this);
thread = new AnimationThread(holder, context, new Handler() {
});

setFocusable(true);
}

@Override
public boolean onTouchEvent(MotionEvent event){
thread.doTouch(event);
return super.onTouchEvent(event);
}

public AnimationThread getThread() {
return thread;
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
thread.setSurfaceSize(width, height);
}

public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
}

public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
}

[/xml]

Step :8 Run your application It will look like this on touch even.
Most of function, varible names are self explanitory . If still you are getting any problem to understand it
write me in our forum section.
2

Tags: , , ,