简体   繁体   中英

Gridworld find closest location in list

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM