开发者

Android Development: Game background loop

I'm developing a 2d Game using Canvas/Surfaceview and have a problem with thread. So what I want to accomplish is something in the background that is for example: for each second SpawnEnemy() or ticking seconds or attacking.

I tried Thread.wait but that just cause pain and make my game 2fps.

here is my gameLoop:

import android.graphics.Canvas;

public class GameLoopThread extends Thread {
       static final long FPS = 20;
       private GameView view;
       private boolean running = 开发者_开发百科false;

       public GameLoopThread(GameView view) {
             this.view = view;
       }

       public void setRunning(boolean run) {
             running = run;
       }

       @Override
       public void run() {
             long ticksPS = 1000 / FPS;
             long startTime;
             long sleepTime;
             while (running) {
                    Canvas c = null;
                    startTime = System.currentTimeMillis();
                    try {
                           c = view.getHolder().lockCanvas();
                           synchronized (view.getHolder()) {
                                  view.onDraw(c);
                           }
                    } finally {
                           if (c != null) {
                                  view.getHolder().unlockCanvasAndPost(c);
                           }
                    }

                    sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
                    try {
                           if (sleepTime > 0)
                                  sleep(sleepTime);
                           else
                                  sleep(10);
                    } catch (Exception e) {}
             }
       }
}

So I want something that is ticking in the background (seconds) that doesn't thread.wait.


You should make your thread run the game normally about 60fps, see this example: How can I use the animation framework inside the canvas?

If you want for each second to do something then you either count frames in onDraw(), on each 60th frame do it, or if you need a greater precision then in each onDraw() check the system time and do something when a second has elapsed.

You should also consider using two methods one for drawing onDraw() and another for the game logic which are called from your thread.


you could use AsyncTask for something to run in background

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜