How can I check if the player throws or drink a specific potion? I want to cancel some specific potions to be used in my project.
As far as I know, there isn't a method call when the player tries to throw a potion, nor when he finishes drinking it.
I have found a method that is called when the player Right Click an Item, but I want to detect only when it is drank or thrown.
How can I cancel the events that I want?
To verify if a player consumed a potion you can use a PlayerItemConsume event
:
@EventHandler
public void onItemConsume (PlayerItemConsumeEvent e) {
ItemStack consumed = e.getItem();
//Make your checks if this is the Potion you want to cancel
if (/*conditions*/) e.setCancelled(true); //Will cancel the potion drink, not applying the effects nor using the item.
}
To check which potion was thrown by a player, you can use a ProjectileLaunchEvent
@EventHandler
public void onProjectileLaunch(ProjectileLaunchEvent e) {
Projectile projectile = e.getEntity();
//Make the checks to know if this is the potion you want to cancel
if (/*conditions*/) e.setCancelled(true); //Cancels the potion launching
}
For example, if I want to cancel the drink action of a Health Potion:
@EventHandler
public void onItemConsume (PlayerItemConsumeEvent e) {
ItemStack consumed = e.getItem();
if (consumed.getType.equals(Material.POTION) {
//It's a potion
Potion potion = Potion.fromItemStack(consumed);
PotionType type = potion.getType();
if (type.equals(PotionType.INSTANT_HEAL) e.setCancelled(true);
}
}
And if I want to Cancel a PotionThrow:
@EventHandler
public void onProjectileLaunch(ProjectileLaunchEvent e) {
Projectile projectile = e.getEntity();
if (projectile instanceof ThrownPotion) {
//It's a Potion
ThrownPotion pot = (ThrownPotion) projectile;
Collection<PotionEffect> effects = pot.getEffects();
for (PotionEffect p : effects) {
if (p.getType().equals(PotionEffectType.INSTANT_HEAL)){
e.setCancelled(true);
break;
}
}
}
}