Introduce Sprite

Sprite
Base on last post Create transparent foreground SurfaceView, the object on foreground was draw as a bitmap. We are going to implement a Sprite class here. Sprite object keep it's own status such as location(x, y) and bitmap, and also draw itself on canvas.

Add class Sprite.java
package com.MyGame;

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;

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

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){
canvas.drawBitmap(bitmap, x-bitmap_halfWidth, y-bitmap_halfHeight, null);
}

}


Modify MyForeground.java
package com.MyGame;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
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) {
mySprite.draw(canvas);
}

}


Next:
- Sprite auto-run

0 Response to "Introduce Sprite"

Posting Komentar