2011-06-20 14 views
2

我只是試圖將球彈回原來的高度。但只要我介紹時間,而不是框架,我就會失去動力。使用時間來增加因重力問題引起的速度(不能獲得完美的彈性)

以代碼下降到了最低限度,我有以下:

public void onDrawFrame(GL10 gl) { 

float timeDelta = System.currentTimeMillis() - startTime; 
startTime = System.currentTimeMillis(); 

update(timeDelta); 
} 

float gravity = -1.0f; 
float PosY = 2400; 
float VelocityY = 0; 

public void update(float timeDelta){ 

PosY+=VelocityY; 
if(PosY<=0){ 
    VelocityY=Math.abs(VelocityY); 
} else{ 
    VelocityY+=gravity*timeDelta; 
}  
Log.d(SystemSingleton.sLogDebug,String.format("Pos: y%f. y%f, timeDelta: %f",PosY, VelocityY, timeDelta)); 

} 

伊夫剩下的時間增量爲毫秒(而不是1000分給我,你會期望秒),以確保我由於施放或四捨五入不會丟失任何東西。

如果我忽略timeDelta並且每幀都應用整個重力,這可以正常工作,它的反彈峯值將是2400(它的起始位置)。但考慮到timedelta,它始終小於2400,並且會逐漸降級,然後在它開始再次降級之前,每次都會跳出一大筆數額(有時超過2400)。

我明顯得到了一些非常嚴重的錯誤,但我看不到它。

任何幫助表示讚賞。

+0

[修正你的時間步長(http://gafferongames.com/game-physics/fix-your-timestep/) – YXD

回答

4

你需要,當你計算出新的崗位上花時間步驟(timeDelta)考慮在內。相反,這樣做的:

PosY += VelocityY; // no!! 

這樣做:

PosY += VelocityY * timeDelta; 

更妙的是,這樣做:

PosY += VelocityY * timeDelta + 0.5 * gravity * timeDelta * timeDelta; 

另外,我會改變反彈的檢測一點點。下面是一些新的代碼嘗試:

// Perform the integration 
PosY  += VelocityY * timeDelta + 0.5 * gravity * timeDelta * timeDelta; 
VelocityY += gravity * timeDelta; 

// Check whether it's time to bounce 
if (PosY<=0 && VelocityY<0){ 
    VelocityY = Math.abs(VelocityY); 
}  
Log.d(...) 
+0

這是完美的工作!非常感謝。 – Steve

0
float timeDelta = System.currentTimeMillis() - startTime; 
startTime = System.currentTimeMillis(); 

我的猜測是這是原因。調用currentTimeMillis可以給你兩個不同的數字。我會做什麼:

float currentTime = System.currentTimeMillis(); 
float delta = currentTime - startTime; 
startTime = currentTime; 
+0

你的方式是更好的,但是這不是主要問題。 – nibot

+0

不是「這個」問題,而是一個「我」應該看到的問題。乾杯。 – Steve