如何添加 1 次射杀小怪兽的附魔?

How to add an enchantment that 1 shots baby mobs?

我已经尝试了很多事件,例如onAttack、EntityDeathEvent、EntityDamageByEntityEvent。 None 其中似乎有效。可能是因为我写错了代码,这就是我想要的。我添加了一个命令,它给你一把带有我试图添加的附魔的钻石剑,该附魔将用于已经应用的 1 次射击婴儿暴民。 代码:

@EventHandler
public void onAttack(EntityDamageByEntityEvent event) {
    Player player = (Player) event.getDamager();
    Ageable ageableEntity = (Ageable) event.getEntity();
    if (event.getEntity() instanceof Ageable) {
        if (ageableEntity.isAdult() == false) {
            if(player.getInventory().getItemInMainHand().containsEnchantment(OrphanEnchants.ORPHAN_OBLITERATOR)) {
                ageableEntity.setLastDamage(1000);
                ageableEntity.setHealth(0);
            }
        }
    }
    
}

告诉我,如果我;以前事件错误,应该选择另一个事件或注册错误的结界。(我知道我没有提供正在注册的代码)

您的代码看起来很可靠,乍一看我看不出它有什么问题(除非您只是没有注册事件)。虽然有破绽。 在转换之前,您可能应该检查 event.getDamager() 是否是 Player 的一个实例。我还建议使用 ageableEntity.damage(damage, player),这样游戏就可以像玩家实际杀死它一样处理它,而不是突然死亡。

我使用了您自己的代码并对其进行了一些更改,并添加了注释以解释所有内容的用途。这只是假设您的代码确实不起作用的替代方案。

    @EventHandler
    public void onAttack(EntityDamageByEntityEvent event) {
        // check if damager is a Player and the entity is Ageable
        // otherwise there's no point of continuing
        if(event.getDamager() instanceof Player && event.getEntity() instanceof Ageable) {
            Player player = (Player) event.getDamager();
            Ageable ageableEntity = (Ageable) event.getEntity();
            // check if they're not an adult and the item has the enchantment required
            // otherwise there's no point of continuing
            if (!ageableEntity.isAdult() && player.getInventory().getItemInMainHand().containsEnchantment(OrphanEnchants.ORPHAN_OBLITERATOR)) {
                // cancel the event to handle it yourself
                event.setCancelled(true);
                
                // remove all potion effects to prevent absorbtion/regeneration/resistance
                // or other potions from keeping the entity alive
                ageableEntity.getActivePotionEffects().stream().map(PotionEffect::getType).forEach(ageableEntity::removePotionEffect);
                
                // set their health very low, but not zero, because then the
                // player doesn't get credit for killing it
                ageableEntity.setHealth(0.5D);
                
                // make the player damage the entity, set damage to MAX_VALUE
                // so the entity MUST die
                ageableEntity.damage(Double.MAX_VALUE, player);
            }
        }
    }