[Solved] Get Coords for a Block a player is looking at?

Discussion in 'Spigot Plugin Development' started by LittleBigBug_, May 6, 2015.

  1. The code I am using


    Code (Text):
    Block b = player.getTargetBlock(null, 5);
    Location loc = b.getLocation();
    Does not work, eclipse underlines and crosses out getTargetBlock
    and says: "The method getTargetBlock(HashSet<Byte>, int) is ambiguous for the type Player"
    Can you please help?


    Thanks in advance!
     
  2. Import the spigot API, not the server
     
    • Informative Informative x 1
  3. Omnivion

    Patron

    Worked fine for me:
    [​IMG]
    Since the getTargetBlock method is deprecated, you should make a method somewhere that you can reference, so you don't have suppresswarnings/deprecation everywhere.
     
  4. clip

    Benefactor

    I have always used a BlockIterator personally. Not sure if it is the proper way but it beats using depreciated methods.

    Code (Text):

        BlockIterator iter = new BlockIterator(player, 10);

        Block lastBlock = iter.next();

        while (iter.hasNext()) {

            lastBlock = iter.next();

            if (lastBlock.getType() == Material.AIR) {
                continue;
            }
            break;
        }
        Location loc = lastBlock.getLocation();
     
    You could create a simple method like so if you plan on calling it a lot:

    Code (Text):
        public final Block getTargetBlock(Player player, int range) {
            BlockIterator iter = new BlockIterator(player, range);
            Block lastBlock = iter.next();
            while (iter.hasNext()) {
                lastBlock = iter.next();
                if (lastBlock.getType() == Material.AIR) {
                    continue;
                }
                break;
            }
            return lastBlock;
        }
     
    #4 clip, May 6, 2015
    Last edited: May 6, 2015
    • Useful Useful x 12
    • Agree Agree x 1
  5. Thanks, I think I had Imported the server on accident


    Thank you clip
    I will use this method instead
    By the way I really like your plugins
     
    • Friendly Friendly x 1
  6. Although the getTagetBlock(HashSet<Byte>) method is deprecated, the getTargetBlock(Set<Material>) method is not. So, you can just cast the null to a Set<Material> and it'll get rid of the deprecation warning:
    Code (Java):
    player.getTargetBlock((Set<Material>) null, 5);
     
    • Informative Informative x 3
    • Useful Useful x 3
    • Agree Agree x 1
  7. Omnivion

    Patron

    Very useful, thank you!
     
    • Informative Informative x 1
    • Optimistic Optimistic x 1