3

Looking for the right event to work with. I want to check if a player right-clicked another player.

This is what i have so far (doesn't work. Not getting into the if or the else statement:

public void onPlayerRightClicks(PlayerInteractEntityEvent e) {
    Player p=e.getPlayer();
    if(e.getRightClicked() instanceof Player) p.sendMessage("You have rightclicked a player.");
    else p.sendMessage("You didn't hit anyone with your spell");
}
131
  • 1,363
  • 1
  • 12
  • 32

2 Answers2

0

Found the answer to the question by combining my own code with codes from another answer on a similar question:

@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerClick(PlayerInteractEvent e) {
    Player p=e.getPlayer();
    NBTItem item = new NBTItem(p.getItemInHand());
    Entity en=getNearestEntityInSight(p,5);
    if(e.getAction()==Action.RIGHT_CLICK_AIR && en instanceof Player) p.sendMessage("You have rightclicked a player.");
    else p.sendMessage("You didn't hit anyone with your spell");
}

public static Entity getNearestEntityInSight(Player player, int range) {
    ArrayList<Entity> entities = (ArrayList<Entity>) player.getNearbyEntities(range, range, range);
    ArrayList<Block> sightBlock = (ArrayList<Block>) player.getLineOfSight(null, range);
    ArrayList<Location> sight = new ArrayList<Location>();
    for (int i = 0;i<sightBlock.size();i++)
        sight.add(sightBlock.get(i).getLocation());
    for (int i = 0;i<sight.size();i++) {
        for (int k = 0;k<entities.size();k++) {
            if (Math.abs(entities.get(k).getLocation().getX()-sight.get(i).getX())<1.3) {
                if (Math.abs(entities.get(k).getLocation().getY()-sight.get(i).getY())<1.5) {
                    if (Math.abs(entities.get(k).getLocation().getZ()-sight.get(i).getZ())<1.3) {
                        return entities.get(k);
                    }
                }
            }
        }
    }
    return null;
}

Even though it works, i don't think it's an optimal answer, as there should be an event that can check whether or not a player rightclicked or at least leftclicked another player. The getNearestEntitySight method finds the closest entity in the player's sight. I combined it with my code which runs when a player rightclicks, using the PlayerInteractEvent.

131
  • 1,363
  • 1
  • 12
  • 32
  • 1
    Seems way too over-complicated to me; I really don't see a point in using `PlayerInteractEvent` instead of `PlayerInteractEntityEvent`. – Cath Jul 06 '17 at 09:47
  • @AscendedKitten `PlayerInteractEntityEvent` doesn't work for players; it just works for mobs. – clabe45 Jun 09 '18 at 05:12
0

Try this:

@EventHandler
public void onPlayerInteractEntity(final PlayerInteractAtEntityEvent e) {
    final Player p = e.getPlayer();
    if (e.getRightClicked() instanceof Player) {
        final Player clicked = (Player) e.getRightClicked();
        // DO STUFF
    }
}