Input Controls

In this section we will modify the GameEngineView to handle input controls. We do this by calling setFocusable(true); on the constructor of the view. All that is left is to override the onKeyDown and onKeyUp events.

[java]
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT )
{
st.setCurrentAnimation("walk_left", true);
st.AnimateTo(new Point( st.getXpos()-40, st.getYpos()));
}
if(keyCode == android.view.KeyEvent.KEYCODE_DPAD_RIGHT)
{
st.setCurrentAnimation("walk_right", true);
st.AnimateTo(new Point( st.getXpos()+40, st.getYpos()));
}

return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if(keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT )
st.setCurrentAnimation("idle_left", false);
if(keyCode == android.view.KeyEvent.KEYCODE_DPAD_RIGHT)
st.setCurrentAnimation("idle_right", false);

st.MoveTo(new Point( st.getXpos(), st.getYpos()));
return super.onKeyUp(keyCode, event);
}
[/java]

In this snippet the “st” object is an Instance of the player object which will be discussed shortly. Note that on key down animate player, on key up we return him to the idle state.

Player

The player class houses the characteristics that a player consists of. We will use the Sprite Tile as the base object, this will take care of the visual part of our player. We will add function and attributes for animation
[java]
package com.warriormill.warriorengine;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;

import com.warriormill.warriorengine.drawable.SpriteTile;

public class Player extends SpriteTile {

public float lifebar=100.0f;
private Point move_to = new Point(10,10);

public Player(int BitmapResourceId, int XmlAnimationResourceId,
Context context) {
super(BitmapResourceId, XmlAnimationResourceId, context);
}
public void AnimateTo(Point pt)
{
move_to = pt;
}
public void MoveTo(Point pt)
{
move_to =pt;
this.setXpos(pt.x);
this.setYpos(pt.y);
}

@Override
public void draw(Canvas canvas) {
super.draw(canvas);

updateLocation();
}
private void updateLocation()
{
if(move_to.y > this.getYpos())
this.setYpos(getYpos()+1);
else if(move_to.y < this.getYpos())
this.setYpos(getYpos()-1);

if(move_to.x > this.getXpos())
this.setXpos(getXpos()+1);
else if(move_to.x < this.getXpos())
this.setXpos(getXpos()-1);
}
}
[/java]

Source Code

Preview

Game Loop

Game Loop is the main part of a game engine, it cycles threw at given intervals updating the game. The Game loop in this section will be fairly simple, it will be a thread that fires off every millisecond.
[java]
/**
*
*/
package com.warriormill.warriorengine;
import java.util.concurrent.TimeUnit;
import com.warriormill.warriorengine.drawable.SpriteTile;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
//import android.view.SurfaceHolder;
//import android.view.SurfaceView;
import android.view.View;

/**
* @author maximo guerrero
*
*/
public class GameEngineView extends View {
SpriteTile st;

GameLoop gameloop;
private class GameLoop extends Thread
{
private volatile boolean running=true;
public void run()
{
while(running)
{
try{
TimeUnit.MILLISECONDS.sleep(1);
postInvalidate();
pause();

}
catch(InterruptedException ex)
{
running=false;
}

}

}
public void pause()
{
running=false;
}
public void start()
{
running=true;
run();
}
public void safeStop()
{
running=false;
interrupt();
}

}
public void unload()
{
gameloop.safeStop();

}

public GameEngineView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
init(context);

}
public GameEngineView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init(context);
}
public GameEngineView(Context context) {
super(context);
// TODO Auto-generated constructor stub
init(context);
}

private void init(Context context)
{
st = new SpriteTile(R.drawable.buster, R.xml.buster, context);
gameloop = new GameLoop();
gameloop.run();

}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
System.out.println("Width " + widthMeasureSpec);
setMeasuredDimension(100, 100);
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
//super.onDraw(canvas);
st.setXpos(15);
st.setYpos(15);

st.draw(canvas);
gameloop.start();

}

}
[/java]
A couple things to notice. We pause the thread until the screen has finished drawing, the reason this is done is that the thread will continue to fire off and the onDraw() function will never be called. Also Since we are using a generic thread and not a UI-Thread we call postInvalidate() function to let android know that our view has to be re drawn.

The Current Game loop is really simple it will call draw on the items that implement the Drawable Interface.

Sprite Tile Class

The Sprite Tile class will be an object that extends the Drawable interface in the android api. Our Sprite will be composed of two files,  a bitmap file (image of format type jpg, png, gif or bmp) and an xml file that describes its behavior.

Sprite sheet ( check out http://www.retrogamezone.co.uk for sample sprites):

Sprite of Buster Bunny

The sprite sheet is one image with all possible animaitions for our sprite

Xml Description:
[xml]
<?xml version="1.0" encoding="utf-8"?>
<animations>
<animation name="idle" canLoop="true" >
<framerect top="4" left="85" bottom="58" right="115" delayNextFrame="10" />
<framerect top="4" left="122" bottom="58" right="153" delayNextFrame="10" />
<framerect top="4" left="161" bottom="58" right="190" delayNextFrame="5" />
<framerect top="4" left="199" bottom="58" right="228" delayNextFrame="5" />
<framerect top="4" left="237" bottom="58" right="268" delayNextFrame="5" />
<framerect top="4" left="276" bottom="58" right="307" delayNextFrame="5" />
<framerect top="4" left="85" bottom="58" right="115" delayNextFrame="60" />

<collisionrect top="10" left="5" bottom="40" right="20" />
</animation>
</animations>
[/xml]
The xml description file contains the information needed to animation the sprite sheet. All of the Elements and there Attributes will have respective fields in our sprite class. Note that the frame rectangle is not equally uniform, this allows to compose an animation where the tile thats being drawn doesn’t have to be the same size. It also tells us how much time each frame will last on the screen, along with a rectangle for collision for that specific animation.

Sprite Class:
The following class will load, draw and animate the tilesheet.
[java]
package com.warriormill.warriorengine.drawable;

import java.util.ArrayList;
import java.util.Hashtable;

import org.xmlpull.v1.XmlPullParser;

import android.content.Context;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.Log;

/**
* @author maximo guerrero
*/
public class SpriteTile extends Drawable {
private Bitmap tileSheet; //sprite tile sheet for all animations. rectangles are used to slip and only show parts of one bitmap
private Hashtable animations; //all animation sequences for this sprite
private String currentAnimation="idle"; //current animation sequence
private int currentFrame=0; //current frame being played
private int xpos=100; // x position
private int ypos=100; // y position
private int waitDelay=0; // delay before the next frame

private ColorFilter cf;

// Class contains Information about one frame
private class FrameInfo
{
public Rect rect = new Rect();
public int nextFrameDelay =0;
}
//Class encapsulates all the data for an animations sequence. List for frames, animcation name, if the sequence will loop and collission info
private class AnimationSequece
{
public ArrayList sequence;
public Rect collisionRect;
public boolean canLoop =false;
@SuppressWarnings("unused")
public String name="idle";
}

//takes resource ids for bitmaps and xmlfiles
public SpriteTile(int BitmapResourceId, int XmlAnimationResourceId, Context context)
{
loadSprite(BitmapResourceId,XmlAnimationResourceId,context);
}

//load bitmap and xml data
public void loadSprite(int spriteid, int xmlid, Context context) {
tileSheet = BitmapFactory.decodeResource(context.getResources(), spriteid);
//load the xml will all the frame animations into a hashtable
XmlResourceParser xpp= context.getResources().getXml(xmlid);

animations= new Hashtable();

try
{
int eventType = xpp.getEventType();
String animationname="";
AnimationSequece animationsequence = new AnimationSequece();
while (eventType != XmlPullParser.END_DOCUMENT){

if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");

} else if(eventType == XmlPullParser.END_DOCUMENT) {
System.out.println("End document");

} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
if(xpp.getName().toLowerCase().equals("animation"))
{
animationname=xpp.getAttributeValue(null, "name");
animationsequence = new AnimationSequece();
animationsequence.name=animationname;
animationsequence.sequence=new ArrayList();
animationsequence.canLoop = xpp.getAttributeBooleanValue(null,"canLoop", false);
}
else if(xpp.getName().toLowerCase().equals("framerect"))
{
FrameInfo frameinfo = new FrameInfo();
Rect frame = new Rect();
frame.top = xpp.getAttributeIntValue(null, "top", 0);
frame.bottom = xpp.getAttributeIntValue(null, "bottom", 0);
frame.left = xpp.getAttributeIntValue(null, "left", 0);
frame.right = xpp.getAttributeIntValue(null, "right", 0);
frameinfo.rect = frame;
frameinfo.nextFrameDelay = xpp.getAttributeIntValue(null,"delayNextFrame", 0);
animationsequence.sequence.add(frameinfo);
}
else if(xpp.getName().toLowerCase().equals("collisionrect"))
{
Rect colrect = new Rect();
colrect.top = xpp.getAttributeIntValue(null, "top", 0);
colrect.bottom = xpp.getAttributeIntValue(null, "bottom", 0);
colrect.left = xpp.getAttributeIntValue(null, "left", 0);
colrect.right = xpp.getAttributeIntValue(null, "right", 0);
animationsequence.collisionRect=colrect;
}
}else if(eventType == XmlPullParser.END_TAG) {
if(xpp.getName().toLowerCase().equals("animation"))
{
animations.put(animationname, animationsequence);
}
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());

}
eventType = xpp.next();
}
}
catch (Exception e) {
Log.e("ERROR", "ERROR IN SPRITE TILE CODE:"+e.toString());
}
System.out.println("Sprite Loaded ");
}
//Draw sprite onto screen
@Override
public void draw(Canvas canvas) {
try
{
FrameInfo frameinfo= animations.get(currentAnimation).sequence.get(currentFrame);
Rect rclip = frameinfo.rect;
Rect dest = new Rect(this.getXpos(), getYpos(), getXpos() + (rclip.right – rclip.left),
getYpos() + (rclip.bottom – rclip.top));
if(cf!=null)
{
//color filter code here

}
canvas.drawBitmap(tileSheet, rclip, dest, null);
update(); //after drawing update the frame counter
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN SPRITE TILE CODE:"+e.toString()+e.getStackTrace().toString());
}

}

@Override
public int getOpacity() {
// TODO Auto-generated method stub
return 100;
}

@Override
public void setAlpha(int alpha) {
// TODO Auto-generated method stub

}

@Override
public void setColorFilter(ColorFilter cf) {
// TODO Auto-generated method stub
this.cf = cf;
}

//updates the frame counter to the next frame
public void update()
{
if(waitDelay==0)//if done waiting
{
//set current frame back to the first because looping is possible
if(animations.get(currentAnimation).canLoop &amp;&amp; currentFrame == animations.get(currentAnimation).sequence.size()-1)
currentFrame=0;
else
{
currentFrame++; //go to next frame

FrameInfo frameinfo= animations.get(currentAnimation).sequence.get(currentFrame);
waitDelay = frameinfo.nextFrameDelay; //set delaytime for the next frame
}
}
else
{
waitDelay–; //wait for delay to expire
}

}
//has this sprite collided with a rect
public boolean hasCollided(Rect rect)
{
AnimationSequece as = animations.get(currentAnimation);
if( rect.right &lt; as.collisionRect.left )
return false;
if( rect.left &gt; as.collisionRect.right )
return false;

if( rect.top &gt; as.collisionRect.bottom )
return false;
if( rect.bottom &lt; as.collisionRect.top )
return false;

return true;
}
//has animation finished playing, returns true on a animaiton that can loop for ever
public boolean hasAnimationFinished()
{
AnimationSequece as = animations.get(currentAnimation);
if(currentFrame == as.sequence.size() -1 &amp;&amp; !as.canLoop )
return true;

return false;
}

public void setXpos(int xpos) {
this.xpos = xpos;
}

public int getXpos() {
return xpos;
}

public void setYpos(int ypos) {
this.ypos = ypos;
}

public int getYpos() {
return ypos;
}
}
[/java]

The class also implements a couple useful functions for checking the animations current state. Also note that the constructor take Resource-ID’s and not file paths. This is so that the developer has the choice of passing in images that have been compressed by the android api or raw images.

Final product:
Android Game Development part 1 - Final Product

That’s it for part 1.

Source Code