1.12.2 Detect left click on ground item (entity)

Discussion in 'Spigot Plugin Development' started by KleinWunder, Feb 25, 2021.

  1. Hello everyone!

    I coded it so that there is a corpse whenever a player dies. It it an item that can not be picked up.

    How can I detect if a player is punching or right-clicking it?

    I thought about maybe using PlayerInteractEvent to get the getRightClickedBlock() Location and getY() +1 and check for an entity on that coordinate. Do you guys know a better way?
  2. You can detect right clicks by listening for the PlayerInteractEntityEvent. And here's how you detect the left clicks:
    Code (Java):
    public void onPlayerInteract(PlayerInteractEvent event) {
        if (event.getPlayer().getGameMode() != GameMode.SPECTATOR && (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK)) { // Listen for all left clicks
            double reach = event.getPlayer().getGameMode() == GameMode.CREATIVE ? 5.0 : 4.0; // The creative mode's reach is 5 unlike the others
            Location eyeLocation = event.getPlayer().getEyeLocation();

            RayTraceResult entityResult = event.getPlayer().getWorld().rayTraceEntities(eyeLocation, event.getPlayer().getLocation().getDirection(), reach, entity -> !entity.getUniqueId().equals(event.getPlayer().getGameMode())); // Get the entity the player's looking at
            RayTraceResult blockResult = event.getPlayer().rayTraceBlocks(reach); // Get the block the player's looking at

            if (entityResult != null && (blockResult == null || entityResult.getHitPosition().distance(eyeLocation) < blockResult.getHitPosition().distance(eyeLocation)) { // Check if we have hit an entity, and if the block is farther than the entity
                Entity entity = entityResult.getHitEntity();
                if (entity instanceof Item) { // Check if the hit entity is an item
                     Item item = (Item) entity; // And here you have your item