嗨,我正在尝试用画布和位图制作一个小游戏,我希望我的游戏在所有设备上运行相同,我发现增量时间是实现这一点的最佳实践,但出于某种原因,当我试图实现它到我的代码中时,我有一些显示问题,例如,我试图在天空中移动我的渐开线,但是当我添加增量时,它们都是散乱的,我不知道我是否做错了,所以请有人帮我把代码标记出来。
private float c1x = 0.0f;
private float c2x = cloudWidth;
private float c3x = cloudWidth * 2;
private float cloudSpeed = 0.1f;
private long curentTime;
private long lastTime = 0;
private double delta;
@Override
public void run(){
while(running){
if(!holder.getSurface().isValid()){
continue;
}
curentTime = System.nanoTime();
delta = curentTime - lastTime;
lastTime = curentTime;
cloudMovement();
canvas = holder.lockCanvas();
canvas.drawBitmap(bg, 0, 0, null);
canvas.drawBitmap(sun, 20, 20, null);
canvas.drawBitmap(cloud1, c1x, c1y, null);
canvas.drawBitmap(cloud2, c2x, c2y, null);
canvas.drawBitmap(cloud3, c3x, c3y, null);
holder.unlockCanvasAndPost(canvas);
}
}
private void cloudMovement(){
if(c1x <= 0 - cloudWidth){
c1x = w;
c1y = y.nextInt(rand);
}
if(c2x <= 0 - cloudWidth){
c2x = w;
c2y = y.nextInt(rand);
}
if(c3x <= 0 - cloudWidth){
c3x = w;
c3y = y.nextInt(rand);
}
c1x-=cloudSpeed * delta;
c2x-=cloudSpeed * delta;
c3x-=cloudSpeed * delta;
}发布于 2015-01-25 11:13:50
您可以使用全局FPS机制来代替,它强制在游戏中使用稳定的FPS :)
如果您跟踪FPS,游戏将在任何设备上运行相同的方式,并且您不需要在所有更新过程中包括增量时间。
下面是我在一个旧项目中使用的一个FpsTracker的代码片段:
private static final long SECOND = 1000;
private static final long TARGET_FPS = 40;
private static final long FRAME_PERIOD = SECOND / TARGET_FPS;
private long time = System.currentTimeMillis();
/**
*
* @param startTime
* @return <code>true</code> if the interval between startTime and the time
* when this method was called is smaller or equal to the given
* frame period.
*
* Will return <code>false</code> if the interval was longer.
*/
public boolean doFpsCheck(long startTime) {
if (System.currentTimeMillis() - time >= SECOND) {
time = System.currentTimeMillis();
}
long sleepTime = FRAME_PERIOD
- (System.currentTimeMillis() - startTime);
if (sleepTime >= 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
//TODO handle this properly
e.printStacktrace()
}
return true;
} else {
return false;
}
}如果此方法返回false,则意味着您的操作花费的时间比给一个帧的时间要长。您可以通过检查doFpsCheck返回参数来对此作出反应。
在代码中实现这一点,如下所示:
@Override
public void run()
{
while(running)
{
if(!holder.getSurface().isValid())
{
continue;
}
startTime = System.currentTimeMillis();
cloudMovement();
canvas = holder.lockCanvas();
canvas.drawBitmap(bg, 0, 0, null);
canvas.drawBitmap(sun, 20, 20, null);
canvas.drawBitmap(cloud1, c1x, c1y, null);
canvas.drawBitmap(cloud2, c2x, c2y, null);
canvas.drawBitmap(cloud3, c3x, c3y, null);
holder.unlockCanvasAndPost(canvas);
doFpsCheck(startTime);
}
}顺便说一句-这是一个很好的做法,把你的游戏循环分成pro子过程,一个是更新过程,另一个是抽签过程。对于许多不同的位图,您应该考虑将字段和功能提取到包含draw(Canvas c)和update()方法的单独类中。所以你不会在你的主类中得到一万亿个字段。
https://stackoverflow.com/questions/28135639
复制相似问题