Проблема DeltaTime при запуске программы - PullRequest
0 голосов
/ 15 января 2012

У меня проблема с deltaTime, которую я использовал. Мой код следующий:

public class Time {
    public static float deltaTime = 0;                      
    public static long frameCount = 0;                      
    public static float fixedTime = 0;                     
    public static float fixedDeltaTime = 0.1f;      
    public static float maxDeltaTime = 0.25f;       

}

А теперь в моем MainThread.java в моей функции run ():

 while (running) {
        canvas = null;
        try {
            canvas = this.surfaceHolder.lockCanvas();
            synchronized (surfaceHolder) {
                float newTime = System.nanoTime() / 1000000000.0f;
                Time.deltaTime = frameTime = newTime - currentTime;

                if(frameTime > Time.maxDeltaTime)
                        frameTime = Time.maxDeltaTime;

                currentTime = newTime;

                accumulator += frameTime;

                while(accumulator > Time.fixedDeltaTime)
                { 
                        this.gamePanel.update();   // where the player and my enemy gets updated                         
                        accumulator -= Time.fixedDeltaTime;
                }

                this.gamePanel.render(canvas);
                //Perform all non-physics-related updates here


                ++Time.frameCount;

                framesSkipped = 0;  // resetting the frames skipped

                timeDiff = System.currentTimeMillis() - beginTime;
                // calculate sleep time
                sleepTime = (int)(FRAME_PERIOD - timeDiff);

                    if (sleepTime > 0) {
                            // if sleepTime > 0 we're OK
                            try {
                                    Thread.sleep(sleepTime);    
                            } catch (InterruptedException e) {}
                    }

                    while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
                            // we need to catch up
                            this.gamePanel.update(); // update without rendering
                            sleepTime += FRAME_PERIOD;  // add frame period to check if in next frame
                            framesSkipped++;
                    }

                    if (framesSkipped > 0) {

                            Log.d(TAG, "Skipped:" + framesSkipped);
                    }
                            // for statistics
                            framesSkippedPerStatCycle += framesSkipped;
                            // calling the routine to store the gathered statistics
                            storeStats();
                }
            } finally {
                // in case of an exception the surface is not left in
                // an inconsistent state
                    if (canvas != null) {
                    surfaceHolder.unlockCanvasAndPost(canvas);
                    }
            } //end finally

    } 

}

в gamePanel.update () я получил призывы об обновлении для игрока и моего врага. Теперь моя проблема в том, что в начале моей игры deltaTime чрезвычайно велика и, таким образом, мое движение очень быстрое, потому что у меня в классе врагов в методе обновления есть следующее:

                   x += vX * Time.deltaTime; // velocity * deltaTime
                   y -= vY * Time.deltaTime;
                   //Log.d(TAG, "Time:"+Time.deltaTime+" x: "+x+" y: "+y);
                   vY -= gravity;

Я все делаю правильно, или что-то не так с моей структурой? Спасибо за любую помощь.

1 Ответ

1 голос
/ 15 января 2012

Вам нужно инициализировать currentTime до начала цикла.Вы не показываете, как он инициализируется, но я предполагаю, что он начинается с 0, поэтому на первой итерации цикла deltaTime устанавливается на текущее время, возвращаемое System.nanoTime().

PS IsЕсть ли причина, по которой вы используете System.nanoTime() в одном месте и System.currentTimeMillis() в другом?Кроме того, рассмотрите возможность придерживаться вычисления всего за миллисекунды (или наносекунды) со значениями long и исключения вычислений с плавающей запятой.

...