Jump to content

addEntity is not spawn entities consistently


AMOnDuck

Recommended Posts

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
Link to comment
Share on other sites

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.

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

    • 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;     }  
    • It is an issue with quark - update it to this build: https://www.curseforge.com/minecraft/mc-mods/quark/files/3642325
  • Topics

×
×
  • Create New...

Important Information

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