Feb 12, 2012

Sprite auto-run

In last article Introduce Sprite without movement. In this article, we are going to make it self move.
Sprite auto-run
Modify Sprite.java to make it self random move inside the canvas.
package com.MyGame;
import java.util.Random;

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

public class Sprite {
private Bitmap bitmap;
private int x;
private int y;
float bitmap_halfWidth, bitmap_halfHeight;

Random random = new Random();
private int dirX;
private int dirY;
private int moveX;
private int moveY;

final int MAX = 99;

public Sprite(Bitmap bm, int tx, int ty){
bitmap = bm;
x = tx;
y = ty;
bitmap_halfWidth = bitmap.getWidth()/2;
bitmap_halfHeight = bitmap.getHeight()/2;

if(random.nextBoolean()){
dirX = 1;
}else{
dirX = -1;
}

if(random.nextBoolean()){
dirY = 1;
}else{
dirY = -1;
}

moveX = random.nextInt(MAX) + 1;
moveY = random.nextInt(MAX) + 1;

}

public void setX(int tx){
x = tx;
}

public void setY(int ty){
y = ty;
}

public int getX(){
return x;
}

public int getY(){
return y;
}

public void draw(Canvas canvas){

if(x < 0){
x = 0;
dirX *= -1;
moveX = random.nextInt(MAX) + 1;
}else if(x >= canvas.getWidth()){
x = canvas.getWidth();
dirX *= -1;
moveX = random.nextInt(MAX) + 1;
}

if(y < 0){
y = 0;
dirY *= -1;
moveY = random.nextInt(MAX) + 1;
}else if(y >= canvas.getHeight()){
y = canvas.getHeight();
dirY *= -1;
moveY = random.nextInt(MAX) + 1;
}


canvas.drawBitmap(bitmap, x-bitmap_halfWidth, y-bitmap_halfHeight, null);
}

public void update(){
x += (dirX * moveX);
y += (dirY * moveY);
}

}


Modify MyForeground.java to override updateStates(), call mySprite.update() indirectly. Also note the method onDraw(); because SurfaceView will not remove the old Sprite, so we have to clear the canvas before draw the new Sprite. TO clear canvas with TRANSPARENT background, we can call the method canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR).
package com.MyGame;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.util.AttributeSet;

public class MyForeground extends MyGameSurfaceView {

Sprite mySprite;

public MyForeground(Context context) {
super(context);
init();
}

public MyForeground(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public MyForeground(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}

private void init(){
mySprite = new Sprite(
BitmapFactory.decodeResource(getResources(), R.drawable.icon_me),
100, 100);
}

@Override
protected void onDraw(Canvas canvas) {
//Clear Canvas with transparent background
canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);

mySprite.draw(canvas);
}

@Override
public void updateStates() {
// TODO Auto-generated method stub
mySprite.update();
}

}


Next:
- Implement onTouchEvent() to handle user touch on SurfaceView

2 comments:

Infolinks In Text Ads