我正在制作一个游戏,其中玩家("鲍勃")垂直移动并持续收集硬币.如果玩家没有设法收集任何硬币5秒钟,"鲍勃"开始下降.随着时间的推移,他会更快倒下.
我的问题是:如何跟踪LibGDX(Java)应用程序中的已用时间?
示例代码如下.
public void update (float deltaTime)
{
`velocity.add(accel.x * deltaTime,accel.y*deltaTime);`
position.add(velocity.x * deltaTime, velocity.y * deltaTime);
bounds.x = position.x - bounds.width / 2;
bounds.y = position.y - bounds.height / 2;
if (velocity.y > 0 && state == BOB_COLLECT_COINE)
{
if (state== BOB_STATE_JUMP)
{
state = BOB_STATE_Increase;
stateTime = 0;
}
else
{
if(state != BOB_STATE_JUMP)
{
state = BOB_STATE_JUMP;//BOB_STATE_JUMP
stateTime = 0;
}
}
}
if (velocity.y < 0 && state != BOB_COLLECT_COINE)
{
if (state != BOB_STATE_FALL) {
state = BOB_STATE_FALL;
stateTime = 0;
}
}
if (position.x < 0) position.x = World.WORLD_WIDTH;
if (position.x > World.WORLD_WIDTH) position.x = 0;
stateTime += deltaTime;
}
public void hitSquirrel ()
{
velocity.set(0, 0);
state = BOB_COLLECT_COINE;s
stateTime = 0;
}
public void collectCoine()
{
state = BOB_COLLECT_COINE;
velocity.y = BOB_JUMP_VELOCITY *1.5f;
stateTime = 0;
}
Run Code Online (Sandbox Code Playgroud)
并且将世界级的收集方法称为 -
private void updateBob(float deltaTime, float accelX)
{
diff = collidetime-System.currentTimeMillis();
if (bob.state != Bob.BOB_COLLECT_COINE && diff>2000) //bob.position.y <= 0.5f)
{
bob.hitSquirrel();
}
Run Code Online (Sandbox Code Playgroud)
小智 6
我是这样做的
float time=0;
public void update(deltaTime){
time += deltaTime;
if(time >= 5){
//Do whatever u want to do after 5 seconds
time = 0; //i reset the time to 0
}
}
Run Code Online (Sandbox Code Playgroud)
看到这个答案有很多观点,我应该指出接受答案的问题并提供替代解决方案.
由于下面一行代码导致的舍入,你的"计时器"会慢慢漂移你运行程序的时间越长:
time = 0;
Run Code Online (Sandbox Code Playgroud)
原因是if条件检查时间值是否大于或等于5(由于舍入误差和帧之间的时间可能会有所不同,因此很可能会更大).更强大的解决方案是不"重置"时间,而是减去等待的时间:
private static final float WAIT_TIME = 5f;
float time = 0;
public void update(float deltaTime) {
time += deltaTime;
if (time >= WAIT_TIME) {
// TODO: Perform your action here
// Reset timer (not set to 0)
time -= WAIT_TIME;
}
}
Run Code Online (Sandbox Code Playgroud)
在快速测试期间,您很可能不会注意到这个微妙的问题,但如果您仔细查看事件的时间安排,运行应用程序几分钟就可能会开始注意到它.
| 归档时间: |
|
| 查看次数: |
9443 次 |
| 最近记录: |