tags:

views:

44

answers:

2

I'm try out a few game mechanics and I tried to mimic WoW's periodic events such as "x damage every z seconds". I've used Timers so far to schedule periodic tasks in this case where I'm trying to regenerate health but is it really necessary to pass "this" in order to modify the instance variable, _mana? Do I really need a separate TimerTask class to "regenerate x health every z seconds"?

In C#, I know I would be able to do this by simply creating a timer that handles ticks through a method. How would I do this with Java? Or is this code fine (efficient)?

private int _mana;

public void regenerate(int amount, int rate)
    {
        _regenerator = new Timer();
        _regenerator.scheduleAtFixedRate(new regenerator(this, amount), 0, rate*1000);
}

public class regenerator extends TimerTask
{
    private ManaResource _mr;
    private int _amount = 0;

    public regenerator(ManaResource mr, int amount)
    {
        _mr = mr;
        _amount = amount;
    }

    public void run()
    {
        _mr._mana += _amount;
        System.out.println(_mr._mana);
    }
}
+1  A: 

If regenerator is an inner class to ManaResource then you don't need to pass this as a parameter. Inner classes have an implicit reference to the outer class' this.

To access that this, however, you need to prefix it with the outer class name:

public void run() {
    ManaResource.this._mana += _amount;
}

because the regenerate instance has its own this as well.

I hope that made sense. There were a lot of this' there.

You will need a new TimerTask class for "regenerate x every y seconds"; there is no lightweight way to pass functions around in Java.

Cameron Skinner
I didn't realize you can access "this" from an inner class since I've never read about classes within classes before I started Java.
Gio Borje
+1  A: 

The way that this usually works in most MMOs, there is some kind of a "pulse". Every X seconds, all the periodic stuff happens. For some reason I think that it was 6 seconds in Everquest 2, and 2 seconds in WOW, but it has been a long time since I looked into this stuff in detail :)

What you would want in your game loop, is some kind of check for "is it time to do periodic stuff". You want to happen as soon as possible after your "tick' length has passed. If you decide to do a "tick" every second, then it won't really matter if you do your stuff at 1.0 seconds vs 1.1 seconds.

I would be wary of doing it in a timer or separate thread, as you get all kinds of synchronization issues to deal with. Keep your core logic in a single thread. You can add fancy stuff in more threads later if performance is an issue.

bwawok