简体   繁体   English

Java中的延迟/计时器

[英]Delay/Timer in java

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? 到目前为止,我使用的每种方法都会暂时冻结程序,但是我想让游戏继续运行,我只希望盾布尔在X时间为true,然后在时间到期后返回false,有什么方法可以做这个? Thanks. 谢谢。

    c.removeEntity(tempEnt);
c.removeEntity(this);
Game.shield = true;
// Wait x time and then do the line below;
Game.shield = false;

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;
   }
}

你试过了吗:

Thread.sleep(1000);

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 如果将游戏包装在Swing框架中,则只需使用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(); 您可以使用timer.start(); in whatever method you use to start the game. 您可以通过任何方式开始游戏。

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. 它工作正常,希望对您有帮助。

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

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