Jump to content

Custom food that applies a random effect.


KiwiChris84

Recommended Posts

Hey, I've been trying to make a custom food that gives the player a random potion effect when they consume it However, this hasn't exactly worked out for me the greatest, and I would like to know if I'm going about it all wrong or if there is something I can do with what I have to fix it. Here's my mod.

public class coolNewItem
{
    public static final String MOD_ID = "coolnewitem";
    // Directly reference a slf4j logger
    private static final Logger LOGGER = LogUtils.getLogger();


    public coolNewItem()
    {

        IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus();

        ModItems.register(eventBus);

        eventBus.addListener(this::setup);

        // Register ourselves for server and other game events we are interested in
        MinecraftForge.EVENT_BUS.register(this);
    }

    private void setup(final FMLCommonSetupEvent event)
    {
        // some preinit code
        LOGGER.info("HELLO FROM PREINIT");
        LOGGER.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
    }

}
package net.kiwichris84.items;

import net.kiwichris84.coolnewitem.coolNewItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;

public class ModItems extends Items {
    public static final DeferredRegister<Item> ITEMS =
            DeferredRegister.create(ForgeRegistries.ITEMS, coolNewItem.MOD_ID);

    public static final RegistryObject<Item> EYE_OF_ALWORTH = ITEMS.register("eye_of_alworth",
            ()-> new Item(new Item.Properties().tab(CreativeModeTab.TAB_MISC).food(ModFoods.EYE_OF_ALWORTH)));



    public static void register(IEventBus eventBus){
        ITEMS.register(eventBus);
    }

}
package net.kiwichris84.items;


import net.minecraft.world.food.FoodProperties;


public class ModFoods extends ModItems {
    public static final FoodProperties EYE_OF_ALWORTH = (new FoodProperties.Builder()).fast().nutrition(4).saturationMod(0.2F).alwaysEat().build();
            }
package net.kiwichris84.items;

import com.mojang.bridge.game.GameSession;
import net.kiwichris84.coolnewitem.coolNewItem;
import net.minecraft.client.Session;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.living.LivingEntityUseItemEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.common.Mod;

import java.util.Objects;
@Mod.EventBusSubscriber(modid= coolNewItem.MOD_ID)
public class ModEventListeners {

    @SubscribeEvent
    protected static void onFoodEaten(LivingEntityUseItemEvent.Finish event) {
        if (event.getEntityLiving() instanceof Player) {
            Player player = (Player) event.getEntity();
            player.removeAllEffects();
            if (player.getMainHandItem().getItem().toString().equals("eye_of_alworth")){
                    int random = (int) ((Math.random() * 32) +1);
                    player.addEffect(new MobEffectInstance(Objects.requireNonNull(MobEffect.byId(random)), 1200, 2));}

            }

        }
    }

I know there is a lot of unused imports, I'll fix that later, but the problem's I've seen so far with the project is that it gives two potion effects instead of one, making me think it is firing twice. The wither effect simply doesn't work, the potion icons in the top right don't go away, and that the levitation effect lasts forever. I would assume that these things all stem from the same root issue, so if anyone could help me out I would appreciate it. 

Also, I know I'm not the best coder in the world, this is my first minecraft mod.

Thanks in advance to anyone willing to take the time to help a brother out.

Link to comment
Share on other sites

  1. 53 minutes ago, KiwiChris84 said:
    player.getMainHandItem().getItem().toString().equals("eye_of_alworth")

    why did you check the Item name, you can just compare the Items with the == operator

  2. why did you use LivingEntityUseItemEvent.Finish? you can just override #finishUsingItem in your Item class and perform the action you want there

  3. 1 hour ago, KiwiChris84 said:
    int random = (int) ((Math.random() * 32) +1);

    i would recommend you to avoid constants when working with registries
    you can use something like:

    		List<MobEffect> effects = Lists.newArrayList(ForgeRegistries.MOB_EFFECTS.getValues());
    		MobEffect randomEffect = effects.get(new Random().nextInt(effects.size()));
Link to comment
Share on other sites

1 hour ago, diesieben07 said:
  • Do not create a new Random instance every time.
  • You might want to consider using Iterables.get instead of copying into a list every time.

i know, this was just a simple example how it could be possible to do

Link to comment
Share on other sites

It says that registryobject#get is a static method. Also, when I tried to change to override the Item class extending the class said that there is no default constructor, and implementing the class said that an interface was required and to be honest I'm not familiar enough with setting up an interface class properly.

Link to comment
Share on other sites

here

    @SubscribeEvent
    protected void onFoodEaten(LivingEntityUseItemEvent.Finish event) {
        if (event.getEntityLiving() instanceof Player) {
            Player player = (Player) event.getEntity();
            player.removeAllEffects();
            if (player.getMainHandItem().getItem()== RegistryObject.get(EYE_OF_ALWORTH)){
                    int random = (int) ((Math.random() * 32) +1);
                    player.addEffect(new MobEffectInstance(Objects.requireNonNull(MobEffect.byId(random)), 1200, 2));}

            }

        }
    }

 

Link to comment
Share on other sites

Alright I did that, and now for the  Player player declaration what should I do to fix the variables? now "event" is marked as red

public class ModEventListeners extends Item {

    public ModEventListeners(Properties pProperties) {
        super(pProperties);
    }
    
    @Override
    public ItemStack finishUsingItem(ItemStack pStack, Level pLevel, LivingEntity pLivingEntity) {
        Player player = (Player) event.getEntity();
        if (player.getMainHandItem().getItem()== EYE_OF_ALWORTH.get()){
            int random = (int) ((Math.random() * 32) +1);
            player.addEffect(new MobEffectInstance(Objects.requireNonNull(MobEffect.byId(random)), 1200, 2));}

        return this.isEdible() ? pLivingEntity.eat(pLevel, pStack) : pStack;

 

Link to comment
Share on other sites

package net.kiwichris84.items;


import net.kiwichris84.coolnewitem.coolNewItem;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraftforge.fml.common.Mod;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
@Mod.EventBusSubscriber(modid= coolNewItem.MOD_ID)
public class ModEventListeners extends Item { public ModEventListeners(Properties pProperties) {super(pProperties);}
    @Override
    public @NotNull ItemStack finishUsingItem(@NotNull ItemStack pStack, @NotNull Level pLevel, @NotNull LivingEntity pLivingEntity) {
        if (pLivingEntity instanceof Player) {
            Player player = (Player) pLivingEntity;
            if (player.getMainHandItem().getItem() == ModItems.EYE_OF_ALWORTH.get()) {
                int random = (int) ((Math.random() * 32) + 1);
                player.addEffect(new MobEffectInstance(Objects.requireNonNull(MobEffect.byId(random)), 1200, 2));
                return this.isEdible() ? pLivingEntity.eat(pLevel, pStack) : pStack;
            }
        }
        return this.isEdible() ? pLivingEntity.eat(pLevel, pStack) : pStack;
    }
}

It doesn't seem to be firing now, what should I do?

Link to comment
Share on other sites

package net.kiwichris84.items;


import net.minecraft.world.food.FoodProperties;


public class ModFoods extends ModItems {
    public static final FoodProperties EYE_OF_ALWORTH = (new FoodProperties.Builder()).fast().nutrition(4).saturationMod(0.2F).alwaysEat().build();
            }
package net.kiwichris84.coolnewitem;

import com.mojang.logging.LogUtils;
import net.kiwichris84.items.ModItems;

import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.common.MinecraftForge;

import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;

import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.slf4j.Logger;



// The value here should match an entry in the META-INF/mods.toml file
@Mod(coolNewItem.MOD_ID)
public class coolNewItem
{
    public static final String MOD_ID = "coolnewitem";
    // Directly reference a slf4j logger
    private static final Logger LOGGER = LogUtils.getLogger();


    public coolNewItem()
    {

        IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus();

        ModItems.register(eventBus);

        eventBus.addListener(this::setup);

        // Register ourselves for server and other game events we are interested in
        MinecraftForge.EVENT_BUS.register(this);
    }

    private void setup(final FMLCommonSetupEvent event)
    {
        // some preinit code
        LOGGER.info("HELLO FROM PREINIT");
        LOGGER.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
    }

}
package net.kiwichris84.items;

import net.kiwichris84.coolnewitem.coolNewItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;

public class ModItems extends Items {
    public static final DeferredRegister<Item> ITEMS =
            DeferredRegister.create(ForgeRegistries.ITEMS, coolNewItem.MOD_ID);

    public static final RegistryObject<Item> EYE_OF_ALWORTH = ITEMS.register("eye_of_alworth",
            ()-> new Item(new Item.Properties().tab(CreativeModeTab.TAB_MISC).food(ModFoods.EYE_OF_ALWORTH)));



    public static void register(IEventBus eventBus){
        ITEMS.register(eventBus);
    }

}

These are my other classes for the mod.

Link to comment
Share on other sites

17 minutes ago, KiwiChris84 said:
    public static final RegistryObject<Item> EYE_OF_ALWORTH = ITEMS.register("eye_of_alworth",
            ()-> new Item(new Item.Properties().tab(CreativeModeTab.TAB_MISC).food(ModFoods.EYE_OF_ALWORTH)));

you did not use your Item class in when creating your Item,

also why did you use your ModEventListeners as Item class?

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

    • They were already updated, and just to double check I even did a cleanup and fresh update from that same page. I'm quite sure drivers are not the problem here. 
    • i tried downloading the drivers but it says no AMD graphics hardware has been detected    
    • Update your AMD/ATI drivers - get the drivers from their website - do not update via system  
    • As the title says i keep on crashing on forge 1.20.1 even without any mods downloaded, i have the latest drivers (nvidia) and vanilla minecraft works perfectly fine for me logs: https://pastebin.com/5UR01yG9
    • Hello everyone, I'm making this post to seek help for my modded block, It's a special block called FrozenBlock supposed to take the place of an old block, then after a set amount of ticks, it's supposed to revert its Block State, Entity, data... to the old block like this :  The problem I have is that the system breaks when handling multi blocks (I tried some fix but none of them worked) :  The bug I have identified is that the function "setOldBlockFields" in the item's "setFrozenBlock" function gets called once for the 1st block of multiblock getting frozen (as it should), but gets called a second time BEFORE creating the first FrozenBlock with the data of the 1st block, hence giving the same data to the two FrozenBlock :   Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=head] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@73681674 BlockEntityData : id:"minecraft:bed",x:3,y:-60,z:-6} Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=3, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=2, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} here is the code inside my custom "freeze" item :    @Override     public @NotNull InteractionResult useOn(@NotNull UseOnContext pContext) {         if (!pContext.getLevel().isClientSide() && pContext.getHand() == InteractionHand.MAIN_HAND) {             BlockPos blockPos = pContext.getClickedPos();             BlockPos secondBlockPos = getMultiblockPos(blockPos, pContext.getLevel().getBlockState(blockPos));             if (secondBlockPos != null) {                 createFrozenBlock(pContext, secondBlockPos);             }             createFrozenBlock(pContext, blockPos);             return InteractionResult.SUCCESS;         }         return super.useOn(pContext);     }     public static void createFrozenBlock(UseOnContext pContext, BlockPos blockPos) {         BlockState oldState = pContext.getLevel().getBlockState(blockPos);         BlockEntity oldBlockEntity = oldState.hasBlockEntity() ? pContext.getLevel().getBlockEntity(blockPos) : null;         CompoundTag oldBlockEntityData = oldState.hasBlockEntity() ? oldBlockEntity.serializeNBT() : null;         if (oldBlockEntity != null) {             pContext.getLevel().removeBlockEntity(blockPos);         }         BlockState FrozenBlock = setFrozenBlock(oldState, oldBlockEntity, oldBlockEntityData);         pContext.getLevel().setBlockAndUpdate(blockPos, FrozenBlock);     }     public static BlockState setFrozenBlock(BlockState blockState, @Nullable BlockEntity blockEntity, @Nullable CompoundTag blockEntityData) {         BlockState FrozenBlock = BlockRegister.FROZEN_BLOCK.get().defaultBlockState();         ((FrozenBlock) FrozenBlock.getBlock()).setOldBlockFields(blockState, blockEntity, blockEntityData);         return FrozenBlock;     }  
  • Topics

×
×
  • Create New...

Important Information

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