I am creating a simple bot that collects coins in-game. The code runs under a game-loop so there are 60 ticks p/s
Here is the function that I use to check for the nearest coin (Game object) to be collected:
public GameObject getNearest(ID objectID) {
LinkedList<GameObject> object = new LinkedList<GameObject>();
for (int i = 0; i < handler.object.size(); i++) {
GameObject temp = handler.object.get(i);
if (temp.getId() == objectID) {
object.add(temp);
}
}
if (object.size() == 0)
return null;
else {
GameObject nearest = object.get(0);
for (int i = 0; i < object.size(); i++) {
if (getDistance(this, object.get(i)) < getDistance(this, nearest)) {
nearest = object.get(i);
}
object.remove(i);
}
return nearest;
}
}
What this function would do is check for all the game objects, and add all the once that match the parameter in a list. It then will loop through the list and check for the nearest coin to the bot.
Is my function efficient regarding performance, speed, and memory usage? By calling the object.remove after every check, does it help? (If not, please mention why)
Is it okay that it calls the method 60 times p/s or I should limit it to execute once every 20 frames maybe? The thing is that I want it to be collecting the coins safely in the shortest time possible. Is there anything that I should take into consideration or something to improve in my code??