Solved Nearest Block

Discussion in 'Plugin Development' started by number1_Master, Jun 18, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    number1_Master

    I'm trying to get the nearest Chest within a certain radius, however the current method I'm using will not always get the nearest chest.
    Code:java
    1. ArrayList<Chest> nearChests = new ArrayList<Chest>();
    2. for(int a = -30; a <= 30; a++)
    3. {
    4. for(int b = 0; b <= owner.getWorld().getMaxHeight(); b++)
    5. {
    6. for(int c = -30; c <= 30; c++)
    7. {
    8. Location loc = new Location(owner.getWorld(), a, b, c);
    9. if((loc.getBlock().getType() == Material.CHEST || loc.getBlock().getType() == Material.TRAPPED_CHEST))
    10. nearChests.add((Chest) loc.getBlock().getState());
    11. else continue;
    12. }
    13. }
    14. }

    What I want to do next is loop through all the Chests in the Array nearChests and find the closest one to the player. What's the best way of doing this? I have some ideas but they are not efficient ...

    Thank you!
     
  2. Offline

    chasechocolate

    Use chest.getLocation().distance(player.getLocation()) and save the one with the shortest distance in a variable.
     
  3. Offline

    number1_Master

    Didn't know that was a method! Thanks :p
     
  4. Offline

    chasechocolate

    I fixed my post, it should be chest.getLocation() rather than chest.
     
  5. Offline

    number1_Master

    No worries ... I figured that out on my own :p
     
  6. Offline

    nitrousspark

    you should do .distanceSquared() instead, uses less memory
     
    number1_Master likes this.
Thread Status:
Not open for further replies.

Share This Page