简体   繁体   English

Java:如何在X秒后计算简单事件的时间?

[英]Java: How can I time simple events to happen after X seconds?

I'm playing around with Java and I've got myself a class for an NPC in a game. 我正在玩Java,我在游戏中为自己的NPC上课。 One method is called when they collide with another object: 当一个方法与另一个对象发生碰撞时会调用它们:

public void collided_in_to(Entity ent) {

    if(ent.equals(game.player)) {
        this.speak = "Ouch!";
    }

}

What I want to do, which I figured was going to be simple, is set this.speak to "" after a given amount of seconds. 我想做的事情,我认为很简单,在给定的秒数之后将this.speak设置为"" Coming from a web background, I was looking for an equivalent of Javascripts setTimeout() . 来自网络背景,我正在寻找相当于Javascripts setTimeout()

I've tried using various timer snippets, such as using Swing timers, but in that case it seemed like every timer would call the same public void actionPerformed(ActionEvent e) method, and so with multiple timers for different events I had no way to differentiate between them. 我已经尝试过使用各种计时器片段,比如使用Swing计时器,但在这种情况下,似乎每个计时器都会调用相同的public void actionPerformed(ActionEvent e)方法,因此对于不同的事件我有多个计时器我没办法区分它们。 Others used inline anonymous classes, but then I have no way to pass non-final parameters to it. 其他人使用内联匿名类,但后来我无法将非最终参数传递给它。

Is there something I'm missing for this use case, where I want very small simple things to happen after a set time? 对于这个用例,我是否缺少一些东西,我希望在一段时间后发生非常小的简单事情? (Instance method called, variable set, etc.) (称为实例方法,变量集等)

Thanks! 谢谢!

How about writing you own simple Timer? 写你自己的简单计时器怎么样? I would think of something like this : 我会想到这样的事情:

public class Timer {

long start = 0;
long delay;

public Timer(long delay) {
    this.delay = delay;
}

public void start() {
    this.start = System.currentTimeMillis();
}

public boolean isExpired() {
    return (System.currentTimeMillis() - this.start) > this.delay;
}

}

Then instantiate the Timer class as a class member and call start() when you want to start the timer. 然后将Timer类实例化为类成员,并在想要启动计时器时调用start()。

In your method you call 在你的方法中你打电话

public void collided_in_to(Entity ent) {

    if(ent.equals(game.player)) {
        if(this.timer.isExpired()) this.speak = "";
        else this.speak = "Ouch!";
    }
}

如果你正在使用游戏循环,你可以简单地通过一秒钟验证

Have you considered threads? 你考虑过线程吗? Thread.sleep() can be used fairly effectively to time it. Thread.sleep()可以相当有效地用于计时。

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

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