我使用以下示例(在此处描述)为我的精灵表设置动画。
从示例中我写了我的对象:
public class Sprite {
private int x, y;
private int width, height;
private Bitmap b;
MainGamePanel ov;
int currentFrame = 0;
public Sprite(MainGamePanel mainGamePanel, Bitmap blob) {
this.ov = mainGamePanel;
this.b = blob;
// 1x12
height = b.getHeight();
width = b.getWidth()/12;
x = y = 50;
}
private void update(int dist) {
currentFrame = ++currentFrame % 12;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//return _b;
}
public void draw(int shift, Canvas canvas, int dist) {
update(dist);
int srcX = currentFrame * width;
Rect src = new Rect(srcX, 0, srcX+width, height);
Rect dst = new Rect(x, y+shift, x+width, y+height+shift);
canvas.drawBitmap(b, src, dst, null);
}
在这里,我每 100 毫秒从图像(位图)中提取不同的部分并显示它。
1 -> 2 -> 3 -> 4 -> ... -> 12
所以我的生物用翅膀飞行和移动。
如果我只显示1 个对象,看起来不错,但是当我尝试循环运行 20 个生物时:
Bitmap blob = BitmapFactory.decodeResource(getResources(), R.drawable.sprite3);
for(int i=0; i<20; i++){
spriteList.add(new Sprite(this, blob));
}
....
for(int i=0; i<spriteList.size(); i++){
sprite = spriteList.get(0);
sprite.draw(canvas, dist);
}
根据绘制的对象计数,我的对象开始变慢。
我认为这是因为Thread.sleep(100);
.
我没有看到任何性能问题。
听起来每个对象睡眠都会暂停所有对象。
对于 20 个对象,此睡眠时间增加到 2 秒。
我肯定会使用以下解决方法:
int sleep = 100/spriteList.size();
Thread.sleep(sleep);
但是代码看起来很乱。
谁能帮我解决它?
这是sprite3图像:
[编辑]
也许我需要在单独的线程中创建每个对象?