java - Projectile damage not being cancelled -
i'm trying cancel damage of arrow if player's name in list nopvp
.
@eventhandler public void playerdamageswhentoggledoff(entitydamagebyentityevent e) { player victim = (player) e.getentity(); player damager = (player) e.getdamager(); if (getter.nopvp.contains(victim.getname()) || getter.nopvp.contains(damager.getname())) { e.setcancelled(true); } else if (e.getcause() == damagecause.projectile && getter.nopvp.contains(victim.getname()) || getter.nopvp.contains(damager.getname())) { e.setcancelled(true); } }
this doesn't seem work, when if
statement fine.
the reason why player takes projectile damage despite being in nopvp
list way cast entities. note both e.getentity()
, e.getdamager()
return entity
object , not player
object. casting these variables you're telling plugin instances of player
class without knowing kind of entity are, false because damager , damaged entity can other types of entities (arrows, animals, mobs, etc.).
to fix can make sure in case of event being called, damager or damaged entity instances of players using instanceof
keyword. below updated version of code should work:
@eventhandler public void playerdamageswhentoggledoff(entitydamagebyentityevent e) { if (e.getentity() instanceof player) { // if damaged entity player player victim = (player) e.getentity(); // cast if (e.getdamager() instanceof player) { // if damager player player damager = (player) e.getdamager(); // check if either of them in list, if -> cancel damage if (getter.nopvp.contains(victim.getname()) || getter.nopvp.contains(damager.getname())) { e.setcancelled(true); } // if damager not player, can check if projectile using damage cause // still check whether damaged player in nopvp list } else if (e.getcause() == entitydamageevent.damagecause.projectile && getter.nopvp.contains(victim.getname())) { e.setcancelled(true); } } }
in original code, if player shot arrow @ player, plugin tried cast arrow (the damager entity) player, not possible (the player
class not subclass of arrow
class) thereby causing classcastexception
, causing otherwise correct code after else-if statement not executed.
here classcastexception when cow damaged entity original code:
i added 2 print statements debug purposes after casting of entities. note these statements never reached (therefore never displayed) in case of classcastexception being thrown displayed if both entities happen players , no exception thrown.
with code snippet posted above, if player's name in nopvp list projectile damage cancelled:
note cancels damage of projectiles if damaged player in nopvp list. cancel damage in case of arrow, can check whether damager entity instance of arrow
class. can check whether arrow shot player or entity such skeleton using arrow.getshooter()
, once you've cast damager entity arrow.
Comments
Post a Comment