简体   繁体   中英

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. 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. Coming from a web background, I was looking for an equivalent of 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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