Search code examples
javabukkit

Java Bukkit API - Get LastDamageCause Entity in PlayerMoveMent Event


So I am trying to figure out how to get the last damage cause when a player reaches the void in minecraft. However, I cannot find a way how to get the damager.

So here is my event handler

@EventHandler
public void on(PlayerMoveEvent event)
{
    Player player = (Player)event.getPlayer();

    if (event.getTo().getY() <= 20.0)
    {
        Entity damager = (Player) event.getPlayer().getLastDamageCause().getEntity();

        if(damager instanceof Player)
        {
            if(player.getLastDamageCause().getEntity().equals(damager))
            {
                damager.sendMessage("KILLER WORKING");
                player.sendMessage("WOKRING!!!!");  
            }
        }
    }
}

Somehow when I got damaged (player), it gives both messages. Can anyone help me? Thanks!


Solution

  • You recieve both messages since both the player and damager are the same at that time.

    You get the entity from getLastDamageCause().getEntity(), store it into the damager object. Then check if the damager is equals to the getLastDamageCause().getEntity(), which always will returns true.

    To solve your problem, according to this topic "getEntity() returns the subject of the DamageEvent, not the damager. To get the damager, you need to check:"

    if(player.getLastDamageCause() instanceof EntityDamageByEntityEvent)
        Player damager = ((EntityDamageByEntityEvent) player.getLastDamageCause()).getDamager();
    

    That code returns the player who damages a player, for an entity I do not know. But it seems you only need to check it if it's a player anyway.

    By the way there is no need to cast event.getPlayer() into a player, since it's already a player.