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);
}
}
最佳答案
源位图是 3*4 Sprite 图像的合成。 该 Sprite 在位图中使用 3 个不同的图像,代码将循环显示它们(图像 0、1 和 2)。
currentFrame = ++currentFrame % BMP_COLUMNS; <--how it works..?
currentFrame 将循环遍历值 1..BMP_COLUMNS-1,即 0, 1, 2, 0, 1, 2, ...
int srcX = currentFrame*width; <---how it works..?
int srcY = 2*height; <-----how it works..?
查找要使用的图像的位置。对于这个特定的 Sprite ,有 3 个图像(可能几乎相同,区别可能是闪烁的灯光或类似的东西)。
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..?
计算显示器上的位置。
关于java - 理解 "Sprite' s onDraw()"方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7117575/