嘿我试图每800毫秒创建一个新图标,并随机定位他们的x值,并将他们的y放在android屏幕下方。我想让这些图标在屏幕上垂直移动,但是开始工作我不断将多个图标叠加在一起。任何帮助表示赞赏。
public class GameView extends SurfaceView{
Bitmap icon;
LinkedList<Sprite> balloonList;
Timer spawnTimer;
TimerTask spawnTask;
Random rand;
SurfaceHolder holder;
int spawnTime;
final int SPAWN_DIFFERENCE = 10;
public GameView(Context context){
super(context);
icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
holder = getHolder();
balloonList = new LinkedList<Sprite>();
rand = new Random();
spawnTime = 1;
spawnTimer = new Timer();
spawnTask = new TimerTask() {
@Override
public void run() {
spawnNewBalloon();
}
};
spawnTimer.scheduleAtFixedRate(spawnTask, 800, 800);
}
private void spawnNewBalloon(){
Canvas canvas = holder.lockCanvas();
if(spawnTime == 0){
balloonList.insertTail(new Sprite(icon, rand.nextInt(getWidth() - icon.getWidth() / 2), getHeight()));
balloonList.getTailData().draw(canvas);
spawnTime = SPAWN_DIFFERENCE;
}
else spawnTime--;
if(balloonList.length() == 0){
for(int i = 0; i < balloonList.length(); i++) {
balloonList.getData(i).update(canvas);
}
}
holder.unlockCanvasAndPost(canvas);
}
}
class Sprite{
public Bitmap image;
public int x, y;
public Sprite(Bitmap image, int x, int y){
this.image = image;
this.x = x;
this.y = y;
}
public void draw(Canvas canvas){
canvas.drawBitmap(image, x, y, null);
}
public void update(Canvas canvas){
if(y > 0) y -= 15;
draw(canvas);
}
}