基本上我只是創建一個計時器是float timer += 1 * deltaTime
,它會每秒添加1,但我在使用它時遇到問題。如何在Libgdx上製作精確的定時器?
if(timer < 2){
//do something
}
我想if語句上停止運行代碼時,定時器爲:2秒,買,因爲我不能這樣做,因爲if(timer != 2f)
它甚至不會檢測2種秒鐘,因爲它的速度太快。這意味着我必須提出一個條件timer < 2f
,這是不準確的,並總是給我無法衡量的結果。
基本上我只是創建一個計時器是float timer += 1 * deltaTime
,它會每秒添加1,但我在使用它時遇到問題。如何在Libgdx上製作精確的定時器?
if(timer < 2){
//do something
}
我想if語句上停止運行代碼時,定時器爲:2秒,買,因爲我不能這樣做,因爲if(timer != 2f)
它甚至不會檢測2種秒鐘,因爲它的速度太快。這意味着我必須提出一個條件timer < 2f
,這是不準確的,並總是給我無法衡量的結果。
而不是使用手工定時器爲什麼不使用Task
和布爾?
下面的僞代碼;
boolean stop = false;
Timer.schedule(new Task() {
@Override
public void run() {
stop = true;
}
}, 2f);
然後在你的渲染方法中;
render() {
if (!stop) {
// Freefall
}
}
如果我正確理解你的問題,你希望你的代碼爲X秒處理並沒有更多的(其中X可以是作爲12.556秒浮點值等)。
我打算建議一個單線程的替代方案,如果您有一個自定義Timer類來管理自由落體邏輯,如下所示。它觀察進展情況,如果它看到比持續時間更長的事物,它就會「隱藏」到內部邏輯中,以便您的邏輯僅執行指定的時間量(由於我們正在使用浮點數而在可配置的誤差範圍內) 。
下面的例子演示了這樣的事情沒有(用其他庫有興趣,以防萬一人)使用libGDX,但它是微不足道的換出我的模擬getDeltaTime()
法Gdx.graphics.getDeltaTime()
。
package tech.otter.timing;
/**
* Created by john on 11/20/16.
*/
public class TimingExample {
public static void main(String... args) {
boolean complete = false;
Timer t = new Timer(15f) {
// You could implement your logic here.
@Override
void action(float delta) {
System.out.println(progress);
}
};
while(!complete) {
complete = t.update(getDeltaTime());
}
assert t.progress < t.duration;
assert t.progress + t.errorMargin > t.duration;
}
/**
* Simulates processing time by returning 0-100ms.
* @return The number of milliseconds that have allegedly elapsed since the last call.
*/
public static float getDeltaTime() {
return (float)(Math.random()/10);
}
abstract static class Timer {
private float duration;
protected float progress;
private float errorMargin;
public Timer(float duration) {
this(duration, 0.0001f);
}
public Timer(float duration, float errorMargin) {
this.duration = duration;
this.errorMargin = errorMargin;
this.progress = 0f;
}
/**
* Update the timer based on how long since the last call.
* @param delta The amount of time since the last call.
* @return Whether the timer's progressed has met the duration.
*/
public boolean update(float delta) {
// This if-statement "caps" the delta so that we will never exceed the duration.
if(progress + delta > duration) {
delta = duration - progress;
}
progress += delta;
action(delta);
// Return "true" if the progress is equal to the duration (+/- a small margin just in case since we use floats).
return progress + errorMargin > duration && progress - errorMargin < duration;
}
/**
* Override this method with your game logic.
* You should not call it directly.
* @param delta The amount of time that has elapsed since the timer was last updated.
*/
abstract void action(float delta);
}
}
你應該幾乎永遠不會比較花車和平等雙打,他們不是確切的數字。您向我們展示的一小段代碼對我來說看起來沒問題,您能描述一下「不準確的結果」是什麼意思嗎? –
我試圖製作一個自由落體模擬器,用戶可以輸入自由落體時間,因爲計時器不準確,那麼計算有時會關閉0.1 –
@Todd Sewell我想要if語句完全停止2秒 –