Reputation: 83
Every method I use so far just freeze's my program for the time but I want the game to continue running, I just want the shield boolean to be true for X time and then return to false after the time has expired, is there any way to do this? Thanks.
c.removeEntity(tempEnt);
c.removeEntity(this);
Game.shield = true;
// Wait x time and then do the line below;
Game.shield = false;
Upvotes: 0
Views: 155
Reputation: 6525
You can try this :-
//Your Code here
c.removeEntity(tempEnt);
c.removeEntity(this);
Game.shield = true;
// Wait x time and then do the line below;
int delay = 10000; //delay 10000 milliseconds
try{
Thread.sleep(delay);
}catch(InterruptedException e){
System.out.println("Interrupted ::"+e.getMessage());
}
Game.shield = false;
//Your code here
Its working fine.Hope it will help you.
Upvotes: 0
Reputation: 209004
Since you failed to mention your framework, I'll suggest this. If you wrap your game in Swing framework, just use a javax.swing.Timer
Timer timer = new Timer(delay null);
public Game() {
timer = new Timer(delay, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
Game.stop();
timer.stop();
}
});
}
After the delay time is up, the game will stop. You can use timer.start();
in whatever method you use to start the game.
Upvotes: 0
Reputation: 42176
The people saying you need to look into threading don't quite understand the question, imho.
If you want to give something a timeout in your game, you just have to record the time it started, then check the current time against that start time plus your duration in your game loop. Something like this:
long shieldStartTime;
long shieldDuration = 10000; //10 seconds
void startShield(){
Game.shield = true;
shieldStartTime = System.currentTimeMillis();
}
//advances your game by one frame, whatever your game loop calls
void step(){
//game loop stuff
if(Game.shield && System.currentTimeMillis() > shieldStartTime + shieldDuration){
Game.shield = false;
}
}
Upvotes: 3