【发布时间】:2011-09-22 10:44:35
【问题描述】:
我已经通过 Surfaceview 创建了我的游戏循环。
游戏中的动画在高配置的功能强大的设备上运行得更快,而在低配置的设备上运行得更慢。
所以我尝试计算 FPS,如果 FPS 高则应该有延迟,否则myThreadSurfaceView.onDraw(c);没有延迟@
这是我用于计算的游戏循环线程代码:
private long mLastTime;
/** Variables for the counter */
private int frameSamplesCollected = 0;
private int frameSampleTime = 0;
private int fps = 0;
@Override
public void run() {
while (myThreadRun) {
Canvas c = null;
try {
c = myThreadSurfaceHolder.lockCanvas(null);
synchronized (myThreadSurfaceHolder)
{
long now = System.currentTimeMillis();
if (mLastTime != 0) {
//Time difference between now and last time we were here
int time = (int) (now - mLastTime);
frameSampleTime += time;
frameSamplesCollected++;
//After 10 frames
if (frameSamplesCollected == 10)
{
//Update the fps variable
fps = (int) (10000 / frameSampleTime);
//Reset the sampletime + frames collected
frameSampleTime = 0;
frameSamplesCollected = 0;
}
}
mLastTime = now;
}
if(fps>25)
{
try {
myThreadSurfaceView.onDraw(c);
TimeUnit.MILLISECONDS.sleep(35);
//Thread.sleep(35);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
myThreadSurfaceView.onDraw(c);
}
}
finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
myThreadSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
现在这段代码给出了我想要的输出,有时 FPS 对于高配置和低配置是相同的。设备。我想要的是游戏在高配置和低配置上运行相同。设备。
那么我怎样才能实现我的目标呢?有没有更好的方法来做到这一点?
【问题讨论】:
标签: android canvas surfaceview frame-rate