Reputation: 1
Hello I am making a PirateShip Actor that goes to the nearest treasure chest. using an ArrayList of the chests how would I find the nearest chest to my pirate ship on the grid. Thank you in advance.
Upvotes: 0
Views: 498
Reputation: 485
If you have the PirateShip's Location and an ArrayList of chests, then I would first suggest turning the List of chests into a List of Locations of chests. Then:
Location loc = getLocation();
int lowest = Integer.MAX_VALUE;
Location closest = null;
for(Location l : locs)
{
double dis = Math.sqrt(Math.pow(l.getRow() - loc.getRow(), 2) + Math.pow(l.getCol() - loc.getCol(), 2)); // Distance Formula
if(dis < lowest)
{
lowest = dis;
closest = l;
}
}
This will set closest to the nearest Location in the list, and you can get the chest in that Location using /* insert name of grid here */.get(closest)
Upvotes: 1