Jump to content

Remove enchantment on shield with onPlayerStoppedUsing


nlxdodge

Recommended Posts

I think that I need another way of profiding blast protection to the user for my antifire dragonshield.

 

What I am trying to do is: When the player Hold the shield with "onItemRightClick" . Then I give a blast protection enchantment.

When the player releases the right click with "onPlayerStoppedUsing" I check if the stack has the enchantment. But I don't know how to remove the enchantment.

 

I have looked at player crafting with repairing items (As that removes the enchantment) but they just return a new itemstack, which is not possible (As far as I know) with onPlayerStoppedUsing as the return type is void.

 

There also is no function for this. So if anyone knows how to do this (Or give me a direction to search for). That would be really appreciated.

 

Code for the people who want to read it:

Spoiler

package com.nlxdodge.scrapyard.Items;

import java.util.List;
import com.nlxdodge.scrapyard.Controller;
import net.minecraft.command.CommandException;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Enchantments;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.IItemPropertyGetter;
import net.minecraft.item.ItemShield;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextComponentUtils;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class DragonShield extends ItemShield
{
	public static int potionTime = 25;
	public static int blastProtectionLevel = 3;

	private boolean isBlastProtected = false;
	
	public DragonShield(String unlocalizedName) 
	{
		this.setUnlocalizedName(unlocalizedName);
		this.setRegistryName(unlocalizedName);
		this.setMaxDamage(1440);
		this.setMaxStackSize(1);
		this.addPropertyOverride(new ResourceLocation("blocking"), new IItemPropertyGetter()
        {
            @SideOnly(Side.CLIENT)
            public float apply(ItemStack stack, World worldIn, EntityLivingBase entityIn)
            {
                return entityIn != null && entityIn.isHandActive() && entityIn.getActiveItemStack() == stack ? 1.0F : 0.0F;
            }
        });
	}
	
	@Override
    public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn)
    {
		PotionEffect antiFire = new PotionEffect(MobEffects.FIRE_RESISTANCE, 20 * potionTime, 0, false, false);
		playerIn.addPotionEffect(antiFire);
        ItemStack itemstack = playerIn.getHeldItem(handIn);
        if(isBlastProtected == false) {
        	itemstack.addEnchantment(Enchantments.BLAST_PROTECTION, blastProtectionLevel);
        	isBlastProtected = true;
        }
        playerIn.setActiveHand(handIn);
        return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, itemstack);
    }
	
	@Override
	public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityLivingBase entityLiving, int timeLeft)
    {
		NBTTagList enchantments = stack.getEnchantmentTagList();
        for(NBTBase enchantment : enchantments) {
        	if(enchantment.getId() == Enchantment.getEnchantmentID(Enchantments.BLAST_PROTECTION)) {
        		isBlastProtected = true;
        	}
        }
		entityLiving.removePotionEffect(MobEffects.FIRE_RESISTANCE);
    }
	
	@Override
    public CreativeTabs getCreativeTab()
    {
        return Controller.scrapTab;
    }
	
	@Override 
	public boolean getIsRepairable(ItemStack toRepair, ItemStack repair)
    {
        return repair.getItem() == Items.GOLD_INGOT ? true : super.getIsRepairable(toRepair, repair);
    }
	
	@Override
	public String getItemStackDisplayName(ItemStack stack)
    {	 
		try {
			return TextComponentUtils.processComponent(null, new TextComponentTranslation("item.dragon_shield.name"), null).getFormattedText();
		} catch (CommandException e) {
			return null;
		}
	}
	
	@Override
	public void addInformation(ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced)
    {
		try {
			tooltip.add(TextFormatting.DARK_PURPLE + TextComponentUtils.processComponent(null, new TextComponentTranslation("item.dragon_shield.tooltip"), null).getFormattedText());
		} catch (CommandException e) {
			
		}
    }
	
	@Override 
	public int getItemEnchantability()
    {
        return 2;
    }
	
	@Override
	public boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment)
    {
		if(enchantment == Enchantments.BLAST_PROTECTION) {
			return true;
		}
        return enchantment.type.canEnchantItem(stack.getItem());
    }
}

 

 

Link to comment
Share on other sites

You can get a current Map<Enchantment, Integer> of the enchantments on your desired item using EnchantmentHelper.getEnchantments. The key of the map is the enchantent, and the value is it's level. You can then remove the desired key-value pair from the map(enchantments are singletons) and re-apply the modified map to your item using EnchantmentHelper.setEnchantments.

Alternatively you can manualy get the stack's NBTTagCompound(ItemStack::getTagCompound), get the NBTTagList with a key of ench and a type of NBTTagCompound(10) from it - that is the list of enchantments. Then you can iterate through it's NBTTagCompound tags to find and remove the one you desire. Those NBTTagCompound entries contain 2 tags - a short with a key if id being the numerical enchantment ID and a short with a key of lvl being the enchantment's level.

 

46 minutes ago, nlxdodge said:

private boolean isBlastProtected = false;

You can't use fields like that in your Item class as items are singletons. This field's value will be shared through all items of DragonShield class.

 

47 minutes ago, nlxdodge said:

for(NBTBase enchantment : enchantments) { if(enchantment.getId() == Enchantment.getEnchantmentID(Enchantments.BLAST_PROTECTION))

This won't do what you want it to do. NBTBase::getId returns the ID of the NBTBase, not the enchantment ID.

 

49 minutes ago, nlxdodge said:

if(isBlastProtected == false)

=>

if (!isBlastProtected)

 

  • Like 1
Link to comment
Share on other sites

Thanks for the help and code watch, as I am still learing.

I also changed my code accordingly:

Spoiler

    @Override
    public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn)
    {
    	PotionEffect antiFire = new PotionEffect(MobEffects.FIRE_RESISTANCE, 20 * potionTime, 0, false, false);
	playerIn.addPotionEffect(antiFire);
        ItemStack stack = playerIn.getHeldItem(handIn);
        Map<Enchantment, Integer> enchantments = EnchantmentHelper.getEnchantments(stack);
        if(!enchantments.containsKey(Enchantments.BLAST_PROTECTION)) {
	    enchantments.put(Enchantments.BLAST_PROTECTION, blastProtectionLevel);
	    EnchantmentHelper.setEnchantments(enchantments, stack);
        }
        playerIn.setActiveHand(handIn);
        return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, stack);
    }
	
    @Override
    public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityLivingBase entityLiving, int timeLeft)
    {
	Map<Enchantment, Integer> enchantments = EnchantmentHelper.getEnchantments(stack);
	if(enchantments.containsKey(Enchantments.BLAST_PROTECTION)) {
	    enchantments.remove(Enchantments.BLAST_PROTECTION);
	    EnchantmentHelper.setEnchantments(enchantments, stack);
	}
	entityLiving.removePotionEffect(MobEffects.FIRE_RESISTANCE);
    }

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • me and my friends kinda just threw mods together and ive been trying to fix it for 2 hours but cant figure out the problem it works and starts to load but then crashes after loading "DISPATCHING CONSTRUCT" https://mclo.gs/Ai8dxTa
    • So I've been making this custom modpack for a while now, I accidentally updated everything and now it wont even start the game past the launch screen. I'm sure there's a mod I need to remove or turn off--but I'm not sure which or if there is something else going on. As time has gone on (I'm not sure if this is related) but the framerates have been dropping into the single digits. I'm not sure what to do anymore except possibly start over... I've pasted the crash log it gave me below--I can't find what's causing it. Help please? https://mclo.gs/Bml06zJ
    • Hi, if you still want to see all player's commands, you can also use a plugin like Stalker Plugin for example ( see https://hangar.papermc.io/StalkerPlugin/Stalker ) with /stalk <player> you can directly see a player's commands or /stalkall you will see all player's commands (in game)
    • HOW I FOUND FAVOR IN THE HANDS OF SACLUX COMPTECH SPECIALST.    I was a victim of a phishing scam and lost 3.5 BTC to thieves. I had been investing in Bitcoin for a while and had a significant amount stored in my wallet. One day, I received an email that looked like it was from my wallet provider, asking me to log in and update my account information. I didn't think twice and entered my login credentials. Little did I know, the email was from scammers who had created a fake website that looked identical to my wallet provider's site. They stole my login credentials and drained my wallet. I was devastated. I had invested a lot of money and time into Bitcoin, and it was all gone in an instant. I tried to contact my wallet provider, but they couldn't help me recover my stolen Bitcoins. I also reported the incident to the authorities, but they couldn't do much to help. It was a hard lesson learned until I came across a testimony of a woman about how she got her stolen investment recovered by a hacker called SACLUX COMPTECH SPECIALST, I searched the name on Google and got their contact and contacted them, behold they got my stolen money back within  2 hours. Thanks to SACLUX COMPTECH SPECIALST for their great job. I invite you to visit their website at http:sacluxcomptechspecialst.com/ to learn more about their services. 
    • HOW I FOUND FAVOR IN THE HANDS OF SACLUX COMPTECH SPECIALST.    I was a victim of a phishing scam and lost 3.5 BTC to thieves. I had been investing in Bitcoin for a while and had a significant amount stored in my wallet. One day, I received an email that looked like it was from my wallet provider, asking me to log in and update my account information. I didn't think twice and entered my login credentials. Little did I know, the email was from scammers who had created a fake website that looked identical to my wallet provider's site. They stole my login credentials and drained my wallet. I was devastated. I had invested a lot of money and time into Bitcoin, and it was all gone in an instant. I tried to contact my wallet provider, but they couldn't help me recover my stolen Bitcoins. I also reported the incident to the authorities, but they couldn't do much to help. It was a hard lesson learned until I came across a testimony of a woman about how she got her stolen investment recovered by a hacker called SACLUX COMPTECH SPECIALST, I searched the name on Google and got their contact and contacted them, behold they got my stolen money back within  2 hours. Thanks to SACLUX COMPTECH SPECIALST for their great job. I invite you to visit their website at http:sacluxcomptechspecialst.com/ to learn more about their services. 
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.