简体   繁体   English

在libgdx游戏中设置延迟

[英]set a delay in libgdx game

i have a game(like super jumper, this game is a jumping game) that our character has life. 我有一个游戏(如超级跳投,这个游戏是一个跳跃游戏),我们的角色有生命。 after collision with enemies, his life reduce. 与敌人发生碰撞后,他的生命减少了。 and i want to after 1 sec , calculate the collisions. 我想在1秒后计算碰撞。 i mean in this 1 sec, if my character contact with enemies , nothing happen and he continue his way. 我的意思是在这1秒内,如果我的角色与敌人接触,没有任何事情发生,他继续他的方式。 for this , i define a boolean variable in my GameScreen class, name "collision" and another in Wolrd class, name "collBirds". 为此,我在我的GameScreen类中定义了一个布尔变量,名为“collision”,另一个在Wolrd类中定义名为“collBirds”。 after one contact with enemy collision and collBirds change to true. 一次与敌人碰撞接触后,collBirds变为true。 but i want after 1 sec collistion change to false. 但我想在1秒后将collistion改为false。 i use several things like System.currentTimeMillis() and "for loop",and nothing happen. 我使用System.currentTimeMillis()和“for loop”之类的东西,但没有任何反应。 i'm not so good in java. 我在java方面不太好。

this is my condition: 这是我的条件:

if(World.collBirds == true && collition == false){
        life -= 1;
        lifeString = "Life : " + life;
        World.collBirds = false;
        collition = true;
        for (??? "need to stay here for 1 sec" ???) {
            collition = false;
        }
    }

In some cases you could also want to use com.badlogic.gdx.utils.Timer 在某些情况下,您还可以使用com.badlogic.gdx.utils.Timer

Example usage: 用法示例:

float delay = 1; // seconds

Timer.schedule(new Task(){
    @Override
    public void run() {
        // Do your work
    }
}, delay);

When the first collision occurs, set a float timeSinceCollision = 0; 发生第一次碰撞时,设置float timeSinceCollision = 0;

Then each loop, you will need to add the time since last check to the variable, and check if it's more than a second. 然后每个循环,您需要将自上次检查后的时间添加到变量,并检查它是否超过一秒。

timeSinceCollision += deltaTime;
if(timeSinceCollision > 1.0f) {
    // do collision stuff
} else {
    // ignore the collision
}

If you want to do this in same thread than you can use Thread.sleep(). 如果你想在同一个线程中执行此操作,可以使用Thread.sleep()。 But in this case your current thread will freeze and if this is single thread game, than your whole game will freeze. 但在这种情况下,你的当前线程将冻结,如果这是单线程游戏,那么你的整个游戏将会冻结。 If you don't want your game to freeze for 1 second, than you should spawn the thread and in that thread call the sleep and after sleep, change the flag 如果你不希望你的游戏冻结1秒,那么你应该产生线程并在该线程中调用睡眠并在睡眠后更改标志

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM