2

I am having trouble in creating and displaying multiple game objects on the screen for every 3 seconds. there is no problem when there's only one object but if I want to create multiple, the problem occurs. To explain in detail, There's a main game loop (the one identical with the existing ones on the internet) and in that game loop,in every 3 seconds I want a new object to be created, added to the ArrayList and then update game panel and show all the objects on the screen in every 3 seconds. The code block above works but it is too fast so the screen is filled with images, I want it to be periodic. What must I do? If using a background thread in order to prevent the block of UI thread, how can I do it?

Thanks in advance.

Here's my code block: MAIN THREAD PART:

    while (running) {
        canvas = null;          
        try {
            canvas = this.surfaceHolder.lockCanvas();
            synchronized (surfaceHolder) {
                beginTime = System.currentTimeMillis();

                this.gamePanel.update();

                this.gamePanel.render(canvas);          

            }
        } finally {
            if (canvas != null) {
                surfaceHolder.unlockCanvasAndPost(canvas);
            }
        } // end finally
    }

and Update method in my MainGamePanel class: public void update() {

    int random = 5 + (int) (Math.random() * (200 - 5));
    droid = new Carrier(BitmapFactory.decodeResource(getResources(),
            R.drawable.image), random, 1);
    Carriers.add(Carrier);

    for (int i = 0; i < Carriers.size(); i++) {
        Carrier CarrierTemp = Carriers.get(i);
        CarrierTemp .update();
    }
}
user1111781
  • 133
  • 1
  • 5

1 Answers1

1

Here's a solution that is built on your current code:

Put this in your thread somewhere:

int savedtime = 0;
long lastTime;

in your update() method:

//Calculate time since last update:
long now = System.currentTimeMillis();
savedtime += now - lastTime;
lastTime = now;
if(savedTime > 3000){//if more than three seconds have passed:
    savedTime = 0;
    int random = 5 + (int) (Math.random() * (200 - 5));
    droid = new Carrier(BitmapFactory.decodeResource(getResources(),R.drawable.image), random, 1);
    Carriers.add(Carrier);
}
for (int i = 0; i < Carriers.size(); i++) {
    Carrier CarrierTemp = Carriers.get(i);
    CarrierTemp .update();
}
Mat Nadrofsky
  • 8,289
  • 8
  • 49
  • 73
Jave
  • 31,598
  • 14
  • 77
  • 90