public class Sprite
{
private static final int BMP_COLUMNS = 3;
private static final int BMP_ROWS = 4;
private int x= 0;
private int y= 50;
private int xSpeed= 5;
private GameView gameView;
private Bitmap bmp;
private int width;
private int height;
private int currentFrame = 0;
public Sprite(GameView gameView,Bitmap bmp)
{
this.gameView=gameView;
this.bmp=bmp;
this.width = bmp.getWidth()/BMP_COLUMNS;
this.height = bmp.getHeight()/BMP_ROWS;
}
private void update()
{
if(x > gameView.getWidth() - width - xSpeed)
{
xSpeed = -5;
}
if(x + xSpeed<0)
{
xSpeed=5;
}
x = x + xSpeed;
currentFrame = ++currentFrame % BMP_COLUMNS; <--how it works..?
}
public void onDraw(Canvas canvas)
{
update();
int srcX = currentFrame*width; <---how it works..?
int srcY = 2*height; <-----how it works..?
Rect src = new Rect(srcX,srcY,srcX+width,srcY+height); <--how it works..?
Rect dst = new Rect(x,y,x+width,y+height); <----how it works..?
canvas.drawBitmap(bmp,src,dst,null);
}
}
public class Sprite { private static final int BMP_COLUMNS = 3; private static final
Share
The source bitmap is a composite of 3*4 sprite images.
This sprite uses 3 different images in the bitmap and the code will cycle through them (image 0, 1, and 2).
currentFrame will cycle through the values 1..BMP_COLUMNS-1, i.e. 0, 1, 2, 0, 1, 2, …
Finds the position of the image to use. For this particular sprite there are 3 images (which probably are almost identical, maybe the difference is a blinking light or something like that).
Calculates the position in the source bitmap.
Calculates the position on the display.