surva network: development blog

Articles and news about Minecraft: Bedrock Edition / PocketMine server development


How to get the attacker using PlayerDeathEvent

A frequently asked question in PocketMine-MP plugin development is how the get the attacker of a died player using PlayerDeathEvent, which is not obvious especially for beginners in PocketMine-MP plugin development.

First, we need to listen on the PlayerDeathEvent, which provides us with the killed player. Using the killed player object, we can get the last damage cause.

/**
 * Get the killer of a player on death
 *
 * @param PlayerDeathEvent $ev
 */
public function onPlayerDeath(PlayerDeathEvent $ev): void {
    $diedPlayer = $ev->getPlayer();
    $lastDamageCause = $diedPlayer->getLastDamageCause();

Next, we check if the last damage was caused by an entity (instanceof EntityDamageByEntityEvent). It’s also possible that the attacker already left the game or died itself, so we need to check if it’s null.

    if(!($lastDamageCause instanceof EntityDamageByEntityEvent)) {
        return;
    }

    $killer = $lastDamageCause->getDamager();

    if($killer === null) {
        return;
    }

As a final step, we check if the attacking entity was a player. If it was, we send a message to the attacking player.

    if(!($killer instanceof Player)) {
        return;
    }

    $killer->sendMessage("You've killed a player!");

That’s it! There are some things you need to check, but on the whole, it’s not that difficult.

The full code of getting the attacker in the PlayerDeathEvent function:

/**
 * Get the killer of a player on death
 *
 * @param PlayerDeathEvent $ev
 */
public function onPlayerDeath(PlayerDeathEvent $ev): void {
    $diedPlayer = $ev->getPlayer();
    $lastDamageCause = $diedPlayer->getLastDamageCause();

    if(!($lastDamageCause instanceof EntityDamageByEntityEvent)) {
        return;
    }

    $killer = $lastDamageCause->getDamager();

    if($killer === null) {
        return;
    }

    if(!($killer instanceof Player)) {
        return;
    }

    $killer->sendMessage("You've killed a player!");
}