Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set a delay in libgdx game

Tags:

java

delay

libgdx

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. i mean in this 1 sec, if my character contact with enemies , nothing happen and he continue his way. for this , i define a boolean variable in my GameScreen class, name "collision" and another in Wolrd class, name "collBirds". after one contact with enemy collision and collBirds change to true. but i want after 1 sec collistion change to false. i use several things like System.currentTimeMillis() and "for loop",and nothing happen. i'm not so good in 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;
        }
    }
like image 274
Hosein Avatar asked May 29 '12 11:05

Hosein


2 Answers

In some cases you could also want to use com.badlogic.gdx.utils.Timer

Example usage:

float delay = 1; // seconds

Timer.schedule(new Task(){
    @Override
    public void run() {
        // Do your work
    }
}, delay);
like image 100
Glogo Avatar answered Oct 15 '22 17:10

Glogo


When the first collision occurs, set a 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
}
like image 38
Matsemann Avatar answered Oct 15 '22 18:10

Matsemann