It doesn’t really lag that much in my game but I know that I could reduce alot of lag in my game by having less timers running. The game have multiple timers because it have one timer that updates everything like the players location and alla the obstacles then I have other timers that I use to remove the power ups that you could get, for example I have one timer that have it’s initial delay set to 5000 and when it is runned one time (it will only run one time) it will remove a specific power up and the I have another timer that have it’s initial delay set to 20 000. How would I keep the different delay of each timer but still only using one por at least fever than I use now?
Simple answer: priority queue.
Or feed entites with delta and let them manage themselves according to it.
True, but it’s not as trivial ‘just’ using a PriorityQueue.
import java.util.*;
public class TimeQueue<T> {
private final PriorityQueue<Slot<T>> queue;
public TimeQueue() {
queue = new PriorityQueue<Slot<T>>(11, new Comparator<Slot<T>>() {
@Override
public int compare(Slot<T> o1, Slot<T> o2) {
return o1.time <= o2.time ? -1 : +1; // never return 0
}
});
}
public static class Slot<Q> {
public final long time;
public final Q item;
public Slot(long time, Q item) {
this.time = time;
this.item = item;
}
@Override
public String toString() {
return "Slot[time=" + time + ", item=" + item + "]";
}
}
// --
public int size() {
return queue.size();
}
public void clear() {
queue.clear();
}
public Slot<T> insert(long time, T item) {
Slot<T> slot = new Slot<T>(time, item);
queue.add(slot);
return slot;
}
public T poll(long now) {
return hasItem(now) ? queue.poll().item : null;
}
public Slot<T> pollSlot(long now) {
return hasItem(now) ? queue.poll() : null;
}
public Slot<T> peekSlot() {
return queue.peek();
}
private final boolean hasItem(long now) {
Slot<T> peeked = queue.peek();
return (peeked != null && peeked.time <= now);
}
public List<T> drain() {
List<T> list = new ArrayList<>();
for (Slot<T> slot; (slot = queue.poll()) != null;) {
list.add(slot.item);
}
return list;
}
public List<Slot<T>> drainSlots() {
List<Slot<T>> list = new ArrayList<>();
for (Slot<T> slot; (slot = queue.poll()) != null;) {
list.add(slot);
}
return list;
}
public int remove(T item) {
int count = 0;
for (Iterator<Slot<T>> it = queue.iterator(); it.hasNext();) {
if (item == it.next().item) {
it.remove();
count++;
}
}
return count;
}
public int remove(Filter<T> filter) {
int count = 0;
for (Iterator<Slot<T>> it = queue.iterator(); it.hasNext();) {
if (filter.accept(it.next().item)) {
it.remove();
count++;
}
}
return count;
}
}
TimeQueue<Runnable> eventQueue = new TimeQueue<>();
eventQueue.insert(Game.TICK_TIME + 1000, new Task());
eventQueue.insert(Game.TICK_TIME + 500, new Task());
eventQueue.insert(Game.TICK_TIME + 500, new Task());
eventQueue.insert(Game.TICK_TIME + 2500, new Task());
public void tick(long now) {
while(true) {
Runnable task = eventQueue.poll(now);
if(task == null) {
break;
}
task.run();
}
}