Jump to content

Recommended Posts

Posted (edited)

I'm making an enchantment that causes lightning to be spawn at the location the player is looking when the player rightclicks an item its aplied to which seemed to work fine but after implementing the cooldown on it i ran into a problem: lightning is rarely ever spawned however sometimes it seems to work normally.

Here is my code, the event is at the bottom:

package net.pondsmp.pondweapons.enchantments;

import com.google.gson.internal.$Gson$Preconditions;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.EnchantmentType;
import net.minecraft.entity.CreatureAttribute;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.LightningBoltEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.INBT;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.CooldownTracker;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IWorld;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.living.LivingEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.FMLWorldPersistenceHook;
import net.minecraftforge.fml.common.Mod;
import net.pondsmp.pondweapons.PondWeaponMod;
import net.pondsmp.pondweapons.init.ModEnchantments;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.jmx.Server;
import org.lwjgl.system.CallbackI;

import java.util.ArrayList;
import java.util.Map;

public class Thunder extends Enchantment {
//    private final Enchantment.Rarity rarity= Rarity.VERY_RARE;
//    private final EnchantmentType type = EnchantmentType.WEAPON;
//    private final EquipmentSlotType slots = EquipmentSlotType.MAINHAND;

    private final int minlvl = 1;
    private final int maxlvl = 1;
    private final boolean treasureEnch = true;
    private final boolean curse = false;
    private final boolean tradable = false;
    private final boolean loot = false;
    private final boolean book = false;
    private static CooldownTracker cooldown = new CooldownTracker();

    public Thunder(Rarity rarityIn, EnchantmentType typeIn, EquipmentSlotType[] slots) {
        super(rarityIn, typeIn, slots);
        setRegistryName("thunder");
    }

    public Thunder(Rarity rarityIn, EnchantmentType typeIn, EquipmentSlotType slots) {
        super(rarityIn, typeIn, new EquipmentSlotType[]{slots});
        setRegistryName("thunder");
    }

    /**
     * Returns the minimum level that the enchantment can have.
     */
    @Override
    public int getMinLevel() {
        return this.minlvl;
    }

    /**
     * Returns the maximum level that the enchantment can have.
     */
    @Override
    public int getMaxLevel() {
        return maxlvl;
    }


    /**
     * Calculates the damage protection of the enchantment based on level and damage source passed.
     */
    @Override
    public int calcModifierDamage(int level, DamageSource source) {
        return 0;
    }

    /**
     * Calculates the additional damage that will be dealt by an item with this enchantment. This alternative to
     * calcModifierDamage is sensitive to the targets EnumCreatureAttribute.
     */
    @Override
    public float calcDamageByCreature(int level, CreatureAttribute creatureType) {
        return 0.0F;
    }

    /**
     * Called whenever a mob is damaged with an item that has this enchantment on it.
     */
    public void onEntityDamaged(LivingEntity user, Entity target, int level) {
    }

    /**
     * Whenever an entity that has this enchantment on one of its associated items is damaged this method will be called.
     */
    public void onUserHurt(LivingEntity user, Entity attacker, int level) {
    }

    @Override
    public boolean isTreasureEnchantment() {
        return treasureEnch;
    }

    @Override
    public boolean isCurse() {
        return curse;
    }

    /**
     * Checks if the enchantment can be sold by villagers in their trades.
     */
    @Override
    public boolean canVillagerTrade() {
        return tradable;
    }

    /**
     * Checks if the enchantment can be applied to loot table drops.
     */
    @Override
    public boolean canGenerateInLoot() {
        return loot;
    }

    /**
     * This applies specifically to applying at the enchanting table. The other method {@link #canApply(ItemStack)}
     * applies for <i>all possible</i> enchantments.
     * @param stack
     * @return
     */

    public boolean canApplyAtEnchantingTable(ItemStack stack) {
        return stack.canApplyAtEnchantingTable(this);
    }

    /**
     * Is this enchantment allowed to be enchanted on books via Enchantment Table
     * @return false to disable the vanilla feature
     */

    public boolean isAllowedOnBooks() {
        return book;
    }

    @Mod.EventBusSubscriber(modid = PondWeaponMod.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
    public static class Events{

        @SubscribeEvent
        public static void rightClickEvent(PlayerInteractEvent.RightClickItem event){
            Map<Enchantment, Integer> enchantments = EnchantmentHelper.getEnchantments(event.getPlayer().getHeldItemMainhand());

            if (enchantments.get(ModEnchantments.thunder) != null) {
                if (!cooldown.hasCooldown(event.getPlayer().getHeldItemMainhand().getItem()))
                {
                    cooldown.setCooldown(event.getPlayer().getHeldItemMainhand().getItem(), 600);
                        ArrayList<String> list = new ArrayList<String>();
                        RayTraceResult block = event.getPlayer().pick(250, 0, true);
                        if(block.getType() == RayTraceResult.Type.BLOCK) {
                            BlockPos blockpos = ((BlockRayTraceResult) block).getPos();
                            LightningBoltEntity lightning = EntityType.LIGHTNING_BOLT.create(event.getWorld());
                            lightning.setLocationAndAngles((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ(), (float) 0.0, (float) 0.0);
//                        lightning.setCaster(event.getPlayer());
                            System.out.println(lightning);
                            event.getWorld().addEntity(lightning);
                        }
                    }
                else {
                    System.out.println(cooldown.getCooldown(event.getPlayer().getHeldItemMainhand().getItem(), 0.0f));
                }
                }
            }

        @SubscribeEvent
        public static void tickEvent(TickEvent event){
            cooldown.tick();
        }

    }
}

which when rigthclicking a bit gives the following output:
[01:44:13] [Server thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.38333333
[01:44:13] [Render thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.26
[01:44:13] [Server thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.26
[01:44:13] [Render thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.13333334
[01:44:13] [Server thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.13333334
[01:44:14] [Render thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.04
[01:44:14] [Server thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.04
[01:44:14] [Render thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:177]: LightningBoltEntity['Lightning Bolt'/837, l='ClientLevel', x=522.00, y=69.00, z=-622.00]
[01:44:14] [Server thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.975
[01:44:14] [Render thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.8433333
[01:44:14] [Server thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.8433333
[01:44:15] [Render thread/INFO] [STDOUT/]: [net.pondsmp.pondweapons.enchantments.Thunder$Events:rightClickEvent:182]: 0.6566667

I should probably mention I decided to start modding the day before yesterday so i'm pretty new but I have enough experience with java.

Edited by AMOnDuck
Small fix in code
Posted

So far I've managed to implement your first two points which fixed my problem, I guess it was trying to spawn the entity on the client side and then started the cooldown again which caused it to not execute on the server side, the cooldown also takes the correct amount of ticks now.
I've still had some trouble implementing a capability so I suppose I will post an update once i manage that, or another post if I don't.

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

    • I've already tried it without mods and it works.
    • i never created a world on singleplayer and I don't see a level.dat file, there's a server.dat file though. but i play multiplayer on my minecraft server with my friends.
    • Add crash-reports with sites like https://mclo.gs/   Make a test without any mods - just Forge
    • Also add the level.dat from your worldsave via sites like mediafire
    • It's the little things that get you sometimes, isn't it? I was actually pretty hyped with my new Bluetooth speaker, ready to see just how well it would sound and pump up my playlist while finishing some work. So, like any other tech enthusiast, I connected it to my laptop, where, of course, my crypto wallet was open and logged in. Big mistake. It was a freakish twist of fate that, well, the Bluetooth speaker seemed to have other plans. It began glitching like a broken record, sending my laptop into a frenzy. I tried reconnecting it, and that's when the disaster struck. In some kind of crazy chain of events, I managed to get locked out of my $90,000 Bitcoin wallet. My wallet was still there, but access was completely blocked. As I sat staring at the screen in utter disbelief, my mind wandered to how something so silly could have caused such a huge mess. Cue the panic. Something this simple, such as a glitch with the speaker, and I don't have access to so much money. The whole thing was just utterly absurd, and I couldn't stop playing the scene over and over in my mind, wishing I'd just have waited until work was done to mess with my new gadget. But it was too late; I was locked out, and the financial chaos was real. Luckily, I knew where to go for help. The very first words in my mind were LEEULTIMATEHACKER @ AOL . COM   telegram: LEEULTIMATE   wh@tsapp +1  (715) 314  -  9248  https :// leeultimatehacker. com I had heard very positive feedback about them regarding their capabilities, and they did not even laugh after several minutes of hearing my story, which, let's face it, sounds utterly ridiculous. Instead, they reassured me that they have seen all kinds of scenarios and can be of assistance with mine. Immediately, I relaxed due to their professionalism. They were very calm, efficient, and started working on my case without wasting even a single second. In some days, they called me back to intimate me with the great news that my $90,000 was safely restored and my wallet was back in my hands. The feeling of relief which I felt was beyond description, knowing well that my ridiculous Bluetooth speaker disaster was finally over. I will make sure gadgets and crypto are in two completely different corners: Now I understand that crypto has absolutely nothing to do with gadgets. Thank the heavens, Lee Ultimate Hacker recovered my funds, at the same time teaching me how to be much more cautious in handling wallets this time around. Not getting caught a second time!
  • Topics

×
×
  • Create New...

Important Information

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