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

When I attempted to replace the the .equals toString part of my if statement i recieved this error

Operator '==' cannot be applied to 'net.minecraft.world.item.Item', 'net.minecraftforge.registries.RegistryObject<net.minecraft.world.item.Item>'

ย 

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

    • DAFTAR DAN LOGIN DISINI ย  Hantogel atau handogel adalah bentuk pengumpulan duka uang yang populer di dunia judi online, khususnya dalam permainan slot gacor. Banyak situs judi online yang menawarkan handogel slot gacor, dan sebagai pemain, penting untuk mengetahui cara memilih dan mengakses situs tersebut dengan aman dan amanah. Dalam artikel ini, kami akan membahas cara memilih situs slot gacor online yang berkualitas dan tahu cara mengakses handogelnya.
    • DAFTAR & LOGIN SIRITOGEL Siritogel adalah kumpulan kata yang mungkin baru saja dikenal oleh masyarakat, namun dengan perkembangan teknologi dan banyaknya informasi yang tersedia di internet, kalau kita siritogel (mencari informasi dengan cara yang cermat dan rinci) tentang situs slot gacor online, maka kita akan menemukan banyak hal yang menarik dan membahayakan sama sekali. Dalam artikel ini, kita akan mencoba menjelaskan apa itu situs slot gacor online dan bagaimana cara mengatasi dampaknya yang negatif.
    • This honestly might just work for you @SubscribeEvent public static void onScreenRender(ScreenEvent.Render.Post event) { final var player = Minecraft.getInstance().player; if(!hasMyEffect(player)) return; // TODO: You provide hasMyEffect float f = Mth.lerp(event.getPartialTick(), this.minecraft.player.oSpinningEffectIntensity, this.minecraft.player.spinningEffectIntensity); float f1 = ((Double)this.minecraft.options.screenEffectScale().get()).floatValue(); if(f <= 0F || f1 >= 1F) return; float p_282656_ = f * (1.0F - f1); final var p_282460_ = event.getGuiGraphics(); int i = p_282460_.guiWidth(); int j = p_282460_.guiHeight(); p_282460_.pose().pushPose(); float f = Mth.lerp(p_282656_, 2.0F, 1.0F); p_282460_.pose().translate((float)i / 2.0F, (float)j / 2.0F, 0.0F); p_282460_.pose().scale(f, f, f); p_282460_.pose().translate((float)(-i) / 2.0F, (float)(-j) / 2.0F, 0.0F); float f1 = 0.2F * p_282656_; float f2 = 0.4F * p_282656_; float f3 = 0.2F * p_282656_; RenderSystem.disableDepthTest(); RenderSystem.depthMask(false); RenderSystem.enableBlend(); RenderSystem.blendFuncSeparate(SourceFactor.ONE, DestFactor.ONE, SourceFactor.ONE, DestFactor.ONE); p_282460_.setColor(f1, f2, f3, 1.0F); p_282460_.blit(NAUSEA_LOCATION, 0, 0, -90, 0.0F, 0.0F, i, j, i, j); p_282460_.setColor(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.defaultBlendFunc(); RenderSystem.disableBlend(); RenderSystem.depthMask(true); RenderSystem.enableDepthTest(); p_282460_.pose().popPose(); } ย  Note: Most of this is directly copied from GameRenderer as you pointed out you found. The only thing you'll have to likely do is update the `oSpinningEffectIntensity` + `spinningEffectIntensity` variables on the player when your effect is applied. Which values should be there? Not 100% sure, might be a game of guess and check, but `handleNetherPortalClient` in LocalPlayer has some hard coded you might be able to start with.
    • Dalam dunia perjudian online yang berkembang pesat, mencari platform yang dapat memberikan kemenangan maksimal dan hasil terbaik adalah impian setiap penjudi. OLXTOTO, dengan bangga, mempersembahkan dirinya sebagai jawaban atas pencarian itu. Sebagai platform terbesar untuk kemenangan maksimal dan hasil optimal, OLXTOTO telah menciptakan gelombang besar di komunitas perjudian online. Satu dari banyak keunggulan yang dimiliki OLXTOTO adalah koleksi permainan yang luas dan beragam. Dari togel hingga slot online, dari live casino hingga permainan kartu klasik, OLXTOTO memiliki sesuatu untuk setiap pemain. Dibangun dengan teknologi terkini dan dikembangkan oleh para ahli industri, setiap permainan di platform ini dirancang untuk memberikan pengalaman yang tak tertandingi bagi para penjudi. Namun, keunggulan OLXTOTO tidak hanya terletak pada variasi permainan yang mereka tawarkan. Mereka juga menonjol karena komitmen mereka terhadap keamanan dan keadilan. Dengan sistem keamanan tingkat tinggi dan proses audit yang ketat, OLXTOTO memastikan bahwa setiap putaran permainan berjalan dengan adil dan transparan. Para pemain dapat merasa aman dan yakin bahwa pengalaman berjudi mereka di OLXTOTO tidak akan terganggu oleh masalah keamanan atau keadilan. Tak hanya itu, OLXTOTO juga terkenal karena layanan pelanggan yang luar biasa. Tim dukungan mereka selalu siap sedia untuk membantu para pemain dengan segala pertanyaan atau masalah yang mereka hadapi. Dengan respon cepat dan solusi yang efisien, OLXTOTO memastikan bahwa pengalaman berjudi para pemain tetap mulus dan menyenangkan. Dengan semua fitur dan keunggulan yang ditawarkannya, tidak mengherankan bahwa OLXTOTO telah menjadi pilihan utama bagi jutaan penjudi online di seluruh dunia. Jika Anda mencari platform yang dapat memberikan kemenangan maksimal dan hasil optimal, tidak perlu mencari lebih jauh dari OLXTOTO. Bergabunglah dengan OLXTOTO hari ini dan mulailah petualangan Anda menuju kemenangan besar dan hasil terbaik!
    • Selamat datang diย OLXTOTO,ย situs slot gacorย terpanas yang sedang booming di industri perjudian online. Jika Anda mencari pengalaman bermain yang luar biasa, makaย OLXTOTOย adalah tempat yang tepat untuk Anda. Dapatkan sensasi tidak biasa dengan variasiย slot onlineย terlengkap dan peluang memenangkan jackpotย slot maxwinย yang sering. Di sini, Anda akan merasakan keseruan yang luar biasa dalam bermainย judi slot. DAFTAR OLXTOTO DISINI LOGIN OLXTOTO DISINI AKUN PRO OLXTOTO DISINI ย  Jackpot Slot Maxwin Sering Untuk Peluang Besar Di OLXTOTO, kami tidak hanya memberikan hadiah slot biasa, tapi juga memberikan kesempatan kepada pemain untuk memenangkan jackpotย slot maxwinย yang sering. Dengan demikian, Anda dapat meraih keberuntungan besar dan memenangkan ribuan rupiah sebagai hadiahย jackpot slot maxwinย kami. Jackpot slot maxwinย merupakan peluang besar bagi para pemain judi slot untuk meraih keuntungan yang lebih besar. Dalam permainan kami, Anda tidak harus terpaku pada kemenangan biasa saja. Kami hadir denganย jackpot slot maxwinย yang sering, sehingga Anda memiliki peluang yang lebih besar untuk meraih kemenangan besar dengan hadiah yang menggiurkan. Dalam permainan judi slot, pengalaman bermain bukan hanya tentang keseruan dan hiburan semata. Kami memahami bahwa para pemain juga menginginkan kesempatan untuk meraih keberuntungan besar. Oleh karena itu, OLXTOTO hadir dengan jackpot slot maxwin yang sering untuk memberikan peluang besar kepada para pemain kami. Peluang Besar Menang Jackpot Slot Maxwin Peluang menang jackpot slot maxwin di OLXTOTO sangatlah besar. Anda tidak perlu khawatir tentang batasan atau pembatasan dalam meraih jackpot tersebut. Kami ingin memberikan kesempatan kepada semua pemain kami untuk merasakan sensasi menang dalam jumlah yang luar biasa. Jackpot slot maxwin kami dibuka untuk semua pemain judi slot di OLXTOTO. Anda memiliki peluang yang sama dengan pemain lainnya untuk memenangkan hadiah jackpot yang besar. Kami percaya bahwa semua orang memiliki kesempatan untuk meraih keberuntungan besar, dan itulah mengapa kami menyediakan jackpot slot maxwin yang sering untuk memenuhi harapan dan keinginan Anda. ย  Kesimpulan OLXTOTO adalahย situs slot gacorย terbaik yang memberikan pengalaman bermain judi slot online yang tak terlupakan. Dengan variasi slot online terlengkap dan peluang memenangkan jackpot slot maxwin yang sering, OLXTOTO menjadi pilihan terbaik bagi para pemain yang mencari kesenangan dan kemenangan besar dalam perjudian online. Di samping itu, OLXTOTO juga menawarkan layanan pelanggan yang ramah dan responsif, siap membantu setiap pemain dalam mengatasi masalah teknis atau pertanyaan seputar perjudian online. Kami menjaga integritas game dan memberikan lingkungan bermain yang adil serta menjalankan kebijakan perlindungan pelanggan yang cermat. Bergabunglah dengan OLXTOTO sekarang dan nikmati pengalaman bermain slot online yang luar biasa. Jadilah bagian dari komunitas perjudian yang mengagumkan ini dan raih kesempatan untuk meraih kemenangan besar. Dapatkan akses mudah dan praktis ke situs OLXTOTO dan rasakan sensasi bermain judi slot yang tak terlupakan. ย 
  • Topics

×
×
  • Create New...

Important Information

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