Reputation: 21134
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);
}
}
Upvotes: 2
Views: 180
Reputation: 15367
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.
Upvotes: 1
Reputation: 54516
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.
Upvotes: 1