简体   繁体   English

java中的计时器(动作延迟)

[英]Timer in java (delay on actions)

so I have this small 2d game I just work on.所以我有这个小型 2d 游戏,我只是在做。 I'm not that good in java but I do understand alot.我在 Java 方面不是那么好,但我确实了解很多。 But I want to make it so when my character fires a bullet he cant fire anymore for 2 seconds.但我想让它当我的角色发射子弹时,他不能再发射 2 秒。 Or whatever delay.或任何延迟。 I have tried multiple things but it simply wouldn't work with what I was trying to achieve.我尝试了多种方法,但它根本无法实现我想要实现的目标。 This is what I use to fire the bullet.这就是我用来发射子弹的东西。

    if (Mouse.next() && Mouse.isButtonDown(0)) {
        t.scheduleAtFixedRate(task, 0, 10000);
        Game.bullets.add(new Bullet(new Vector2f(position.x + 25, position.y + 19), new Vector2f(position.x, 0)));
    }

Thanks谢谢

  1. Create class variable for storing last shot time创建用于存储上次拍摄时间的类变量
  2. Save last shot time in this variable在此变量中保存上次拍摄时间
  3. Compare current time and variable's value on shooting event and decide is it permitted to shot again or not.比较当前时间和变量在射击事件上的值,决定是否允许再次射击。

Something like:就像是:

if (Mouse.next() && Mouse.isButtonDown(0) && (System.currentTimeMillis() - lastShotTime >= 2000)) {
    t.scheduleAtFixedRate(task, 0, 10000);
    Game.bullets.add(new Bullet(new Vector2f(position.x + 25, position.y + 19), new Vector2f(position.x, 0)));
    lastShotTime = System.currentTimeMillis();
}

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

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