(BUKKIT) The method getTargetBlock isn't working

3.4k views Asked by At

I think (hope) I'm using the correct arguments. player.getTargetBlock is needed for lots of things in bukkit, but it never works for me! The only time it works is with a lightning bolt spawner.

Here is the bit that doesn't work:

@EventHandler
public void onPlayerInteractBlockTeleport(PlayerInteractEvent event) {
    Player player = event.getPlayer();
    if (player.getItemInHand().getType() == Material.BONE) {
        player.getWorld().teleport(player.getTargetBlock(null, 200));
        player.playSound(player.getLocation(), Sound.ENDERMAN_TELEPORT, 10, 1);
    }
}

Anyone help?

1

There are 1 answers

9
Adrian Sohn On

There are three reasons as to why your code most likely won't work:

  1. You're attempting to teleport the player's "world" (player.getWorld().teleport) and not the player itself. As far as I can tell from the Bukkit 1.8.3 API, there is no teleport() method for worlds. I'm assuming you are trying to teleport the player in which case player.teleport(location/entity) will work.

  2. The teleport() method takes a location or entity as an argument, not a block. You'll need to pass it the location of the target block with block.getLocation().

  3. Depending on which version of Bukkit you are using and whether you are also using Craftbukkit, you should probably cast the first argument of the getTargetBlock() method to a Set in order to avoid ambiguity (there is another method (deprecated) which takes a HashSet as the first argument).

In your event method, I would also teleport the player to a location above the block so as not to teleport the player inside the block. Last but not least, make sure that your event listener class has been registered. Below is some example code that I tested:

@EventHandler
public void onPlayerInteractBlockTeleport(PlayerInteractEvent event) {
    Player player = event.getPlayer();
    //Null check isn't necessary anymore, an empty item will have Material.AIR and getTargetBlock() now also works if no target block is found
    if (player.getItemInHand().getType() == Material.BONE) {
        Location playerLoc = player.getLocation(); //Get the player's location
        Location target = player.getTargetBlock((Set) null, 200).getLocation().clone().add(0, 1, 0); //Get the block location + 1 y
        target.setYaw(playerLoc.getYaw()); //Set the yaw of the target location to the player's yaw
        target.setPitch(playerLoc.getPitch()); //Set the pitch of the target location to the player's pitch
        player.teleport(target); //Teleport player
        player.playSound(player.getLocation(), Sound.ENDERMAN_TELEPORT, 10, 1); //Play sound
    }
}