Jump to content

Custom ItemEntity


tal124

Recommended Posts

I have created a custom ItemEntity, however, no matter what's put into it (100% just vanilla code switched to be mine) Whenever I throw the item it doesn't drop it will pop out of my inventory for not even a millisecond and place back into the spot it was in.

 

Spoiler
public class CoalSwordEntity extends ItemEntity {
    private static final EntityDataAccessor<ItemStack> DATA_ITEM = SynchedEntityData.defineId(CoalSwordEntity.class, EntityDataSerializers.ITEM_STACK);
    private static final int LIFETIME = 6000;
    private static final int INFINITE_PICKUP_DELAY = 32767;
    private static final int INFINITE_LIFETIME = -32768;
    private int age;
    private int pickupDelay;
    private int health = 5;
    @Nullable
    private UUID thrower;
    @Nullable
    private UUID owner;
    public final float bobOffs;
    /**
     * The maximum age of this EntityItem.  The item is expired once this is reached.
     */
    public int lifespan = 6000;

    public CoalSwordEntity(EntityType<? extends ItemEntity> p_31991_, Level p_31992_) {
        super(p_31991_, p_31992_);
        this.bobOffs = this.random.nextFloat() * (float)Math.PI * 2.0F;
        this.setYRot(this.random.nextFloat() * 360.0F);
    }

    public CoalSwordEntity(Level p_32001_, double p_32002_, double p_32003_, double p_32004_, ItemStack p_32005_) {
        this(p_32001_, p_32002_, p_32003_, p_32004_, p_32005_, p_32001_.random.nextDouble() * 0.2D - 0.1D, 0.2D, p_32001_.random.nextDouble() * 0.2D - 0.1D);
    }

    public CoalSwordEntity(Level p_149663_, double p_149664_, double p_149665_, double p_149666_, ItemStack p_149667_, double p_149668_, double p_149669_, double p_149670_) {
        this(EntityType.ITEM, p_149663_);
        this.setPos(p_149664_, p_149665_, p_149666_);
        this.setDeltaMovement(p_149668_, p_149669_, p_149670_);
        this.setItem(p_149667_);
        this.lifespan = (p_149667_.getItem() == null ? 6000 : p_149667_.getEntityLifespan(p_149663_));
    }

    private CoalSwordEntity(CoalSwordEntity entity) {
        super((EntityType<? extends ItemEntity>) entity.getType(), entity.level);
        this.setItem(entity.getItem().copy());
        this.copyPosition(entity);
        this.age = entity.age;
        this.bobOffs = entity.bobOffs;
    }

    @Override
    public boolean occludesVibrations() {
        return this.getItem().is(ItemTags.OCCLUDES_VIBRATION_SIGNALS);
    }
    @Override
    protected Entity.MovementEmission getMovementEmission() {
        return Entity.MovementEmission.NONE;
    }
    @Override
    protected void defineSynchedData() {
        this.getEntityData().define(DATA_ITEM, ItemStack.EMPTY);
    }

    /**
     * Called to update the entity's position/logic.
     */
    @Override
    public void tick() {
        if (getItem().onEntityItemUpdate(this)) return;
        if (this.getItem().isEmpty()) {
            this.discard();
        } else {
            super.tick();
            if (this.pickupDelay > 0 && this.pickupDelay != 32767) {
                --this.pickupDelay;
            }

            this.xo = this.getX();
            this.yo = this.getY();
            this.zo = this.getZ();
            Vec3 vec3 = this.getDeltaMovement();
            float f = this.getEyeHeight() - 0.11111111F;
            if (this.isInWater() && this.getFluidHeight(FluidTags.WATER) > (double)f) {
                this.setUnderwaterMovement();
            } else if (this.isInLava() && this.getFluidHeight(FluidTags.LAVA) > (double)f) {
                this.setUnderLavaMovement();
            } else if (!this.isNoGravity()) {
                this.setDeltaMovement(this.getDeltaMovement().add(0.0D, -0.04D, 0.0D));
            }

            if (this.level.isClientSide) {
                this.noPhysics = false;
            } else {
                this.noPhysics = !this.level.noCollision(this, this.getBoundingBox().deflate(1.0E-7D));
                if (this.noPhysics) {
                    this.moveTowardsClosestSpace(this.getX(), (this.getBoundingBox().minY + this.getBoundingBox().maxY) / 2.0D, this.getZ());
                }
            }

            if (!this.onGround || this.getDeltaMovement().horizontalDistanceSqr() > (double)1.0E-5F || (this.tickCount + this.getId()) % 4 == 0) {
                this.move(MoverType.SELF, this.getDeltaMovement());
                float f1 = 0.98F;
                if (this.onGround) {
                    f1 = this.level.getBlockState(new BlockPos(this.getX(), this.getY() - 1.0D, this.getZ())).getFriction(level, new BlockPos(this.getX(), this.getY() - 1.0D, this.getZ()), this) * 0.98F;
                }

                this.setDeltaMovement(this.getDeltaMovement().multiply((double)f1, 0.98D, (double)f1));
                if (this.onGround) {
                    Vec3 vec31 = this.getDeltaMovement();
                    if (vec31.y < 0.0D) {
                        this.setDeltaMovement(vec31.multiply(1.0D, -0.5D, 1.0D));
                    }
                }
            }

            boolean flag = Mth.floor(this.xo) != Mth.floor(this.getX()) || Mth.floor(this.yo) != Mth.floor(this.getY()) || Mth.floor(this.zo) != Mth.floor(this.getZ());
            int i = flag ? 2 : 40;
            if (this.tickCount % i == 0 && !this.level.isClientSide && this.isMergable()) {
                this.mergeWithNeighbours();
            }

            if (this.age != -32768) {
                ++this.age;
            }

            this.hasImpulse |= this.updateInWaterStateAndDoFluidPushing();
            if (!this.level.isClientSide) {
                double d0 = this.getDeltaMovement().subtract(vec3).lengthSqr();
                if (d0 > 0.01D) {
                    this.hasImpulse = true;
                }
            }

            ItemStack item = this.getItem();
            if (!this.level.isClientSide && this.age >= lifespan) {
                int hook = net.minecraftforge.event.ForgeEventFactory.onItemExpire(this, item);
                if (hook < 0) this.discard();
                else          this.lifespan += hook;
            }

            if (item.isEmpty()) {
                this.discard();
            }

        }
    }

    private void setUnderwaterMovement() {
        Vec3 vec3 = this.getDeltaMovement();
        this.setDeltaMovement(vec3.x * (double)0.99F, vec3.y + (double)(vec3.y < (double)0.06F ? 5.0E-4F : 0.0F), vec3.z * (double)0.99F);
    }

    private void setUnderLavaMovement() {
        Vec3 vec3 = this.getDeltaMovement();
        this.setDeltaMovement(vec3.x * (double)0.95F, vec3.y + (double)(vec3.y < (double)0.06F ? 5.0E-4F : 0.0F), vec3.z * (double)0.95F);
    }

    /**
     * Looks for other itemstacks nearby and tries to stack them together
     */

    private void mergeWithNeighbours() {
        if (this.isMergable()) {
            for(CoalSwordEntity itementity : this.level.getEntitiesOfClass(CoalSwordEntity.class, this.getBoundingBox().inflate(0.5D, 0.0D, 0.5D), (p_186268_) -> {
                return p_186268_ != this && p_186268_.isMergable();
            })) {
                if (itementity.isMergable()) {
                    this.tryToMerge(itementity);
                    if (this.isRemoved()) {
                        break;
                    }
                }
            }

        }
    }

    private boolean isMergable() {
        ItemStack itemstack = this.getItem();
        return this.isAlive() && this.pickupDelay != 32767 && this.age != -32768 && this.age < 6000 && itemstack.getCount() < itemstack.getMaxStackSize();
    }

    private void tryToMerge(CoalSwordEntity p_32016_) {
        ItemStack itemstack = this.getItem();
        ItemStack itemstack1 = p_32016_.getItem();
        if (Objects.equals(this.getOwner(), p_32016_.getOwner()) && areMergable(itemstack, itemstack1)) {
            if (itemstack1.getCount() < itemstack.getCount()) {
                merge(this, itemstack, p_32016_, itemstack1);
            } else {
                merge(p_32016_, itemstack1, this, itemstack);
            }

        }
    }

    public static boolean areMergable(ItemStack pStack1, ItemStack pStack2) {
        if (!pStack2.is(pStack1.getItem())) {
            return false;
        } else if (pStack2.getCount() + pStack1.getCount() > pStack2.getMaxStackSize()) {
            return false;
        } else if (pStack2.hasTag() ^ pStack1.hasTag()) {
            return false;
        } else if (!pStack1.areCapsCompatible(pStack2)) {
            return false;
        } else {
            return !pStack2.hasTag() || pStack2.getTag().equals(pStack1.getTag());
        }
    }

    public static ItemStack merge(ItemStack p_32030_, ItemStack p_32031_, int p_32032_) {
        int i = Math.min(Math.min(p_32030_.getMaxStackSize(), p_32032_) - p_32030_.getCount(), p_32031_.getCount());
        ItemStack itemstack = p_32030_.copy();
        itemstack.grow(i);
        p_32031_.shrink(i);
        return itemstack;
    }

    private static void merge(CoalSwordEntity p_32023_, ItemStack p_32024_, ItemStack p_32025_) {
        ItemStack itemstack = merge(p_32024_, p_32025_, 64);
        p_32023_.setItem(itemstack);
    }

    private static void merge(CoalSwordEntity entity, ItemStack stack, CoalSwordEntity coalSwordEntity, ItemStack itemStack) {
        merge(entity, stack, itemStack);
        entity.pickupDelay = Math.max(entity.pickupDelay, coalSwordEntity.pickupDelay);
        entity.age = Math.min(entity.age, coalSwordEntity.age);
        if (itemStack.isEmpty()) {
            entity.discard();
        }

    }
    @Override
    public boolean fireImmune() {
        return this.getItem().getItem().isFireResistant() || super.fireImmune();
    }

    /**
     * Called when the entity is attacked.
     */
    @Override
    public boolean hurt(DamageSource pSource, float pAmount) {
        if (this.level.isClientSide || this.isRemoved()) return false; //Forge: Fixes MC-53850
        if (this.isInvulnerableTo(pSource)) {
            return false;
        } else if (!this.getItem().isEmpty() && this.getItem().is(Items.NETHER_STAR) && pSource.isExplosion()) {
            return false;
        } else if (!this.getItem().getItem().canBeHurtBy(pSource)) {
            return false;
        } else if (this.level.isClientSide) {
            return true;
        } else {
            this.markHurt();
            this.health = (int)((float)this.health - pAmount);
            this.gameEvent(GameEvent.ENTITY_DAMAGED, pSource.getEntity());
            if (this.health <= 0) {
                this.getItem().onDestroyed(this, pSource);
                this.discard();
            }

            return true;
        }
    }
    @Override
    public void addAdditionalSaveData(CompoundTag pCompound) {
        pCompound.putShort("Health", (short)this.health);
        pCompound.putShort("Age", (short)this.age);
        pCompound.putShort("PickupDelay", (short)this.pickupDelay);
        pCompound.putInt("Lifespan", lifespan);
        if (this.getThrower() != null) {
            pCompound.putUUID("Thrower", this.getThrower());
        }

        if (this.getOwner() != null) {
            pCompound.putUUID("Owner", this.getOwner());
        }

        if (!this.getItem().isEmpty()) {
            pCompound.put("Item", this.getItem().save(new CompoundTag()));
        }

    }

    /**
     * (abstract) Protected helper method to read subclass entity data from NBT.
     */
    @Override
    public void readAdditionalSaveData(CompoundTag pCompound) {
        this.health = pCompound.getShort("Health");
        this.age = pCompound.getShort("Age");
        if (pCompound.contains("PickupDelay")) {
            this.pickupDelay = pCompound.getShort("PickupDelay");
        }
        if (pCompound.contains("Lifespan")) lifespan = pCompound.getInt("Lifespan");

        if (pCompound.hasUUID("Owner")) {
            this.owner = pCompound.getUUID("Owner");
        }

        if (pCompound.hasUUID("Thrower")) {
            this.thrower = pCompound.getUUID("Thrower");
        }

        CompoundTag compoundtag = pCompound.getCompound("Item");
        this.setItem(ItemStack.of(compoundtag));
        if (this.getItem().isEmpty()) {
            this.discard();
        }

    }

    /**
     * Called by a player entity when they collide with an entity
     */
    @Override
    public void playerTouch(Player pEntity) {
        if (!this.level.isClientSide) {
            if (this.pickupDelay > 0) return;
            ItemStack itemstack = this.getItem();
            Item item = itemstack.getItem();
            int i = itemstack.getCount();

            int hook = net.minecraftforge.event.ForgeEventFactory.onItemPickup(this, pEntity);
            if (hook < 0) return;

            ItemStack copy = itemstack.copy();
            if (this.pickupDelay == 0 && (this.owner == null || lifespan - this.age <= 200 || this.owner.equals(pEntity.getUUID())) && (hook == 1 || i <= 0 || pEntity.getInventory().add(itemstack))) {
                copy.setCount(copy.getCount() - getItem().getCount());
                net.minecraftforge.event.ForgeEventFactory.firePlayerItemPickupEvent(pEntity, this, copy);
                pEntity.take(this, i);
                if (itemstack.isEmpty()) {
                    this.discard();
                    itemstack.setCount(i);
                }

                pEntity.awardStat(Stats.ITEM_PICKED_UP.get(item), i);
                pEntity.onItemPickup(this);
            }

        }
    }
    @Override
    public Component getName() {
        Component component = this.getCustomName();
        return (Component)(component != null ? component : new TranslatableComponent(this.getItem().getDescriptionId()));
    }

    /**
     * Returns true if it's possible to attack this entity with an item.
     */
    @Override
    public boolean isAttackable() {
        return false;
    }

    @Nullable
    @Override
    public Entity changeDimension(ServerLevel pServer, net.minecraftforge.common.util.ITeleporter teleporter) {
        Entity entity = super.changeDimension(pServer, teleporter);
        if (!this.level.isClientSide && entity instanceof ItemEntity) {
            ((CoalSwordEntity)entity).mergeWithNeighbours();
        }

        return entity;
    }

    /**
     * Gets the item that this entity represents.
     */
    @Override
    public ItemStack getItem() {
        return this.getEntityData().get(DATA_ITEM);
    }

    /**
     * Sets the item that this entity represents.
     */
    @Override
    public void setItem(ItemStack pStack) {
        this.getEntityData().set(DATA_ITEM, pStack);
    }
    @Override
    public void onSyncedDataUpdated(EntityDataAccessor<?> pKey) {
        super.onSyncedDataUpdated(pKey);
        if (DATA_ITEM.equals(pKey)) {
            this.getItem().setEntityRepresentation(this);
        }

    }

    @Nullable
    @Override
    public UUID getOwner() {
        return this.owner;
    }
    @Override
    public void setOwner(@Nullable UUID pOwnerId) {
        this.owner = pOwnerId;
    }

    @Nullable
    @Override
    public UUID getThrower() {
        return this.thrower;
    }
    @Override
    public void setThrower(@Nullable UUID pThrowerId) {
        this.thrower = pThrowerId;
    }
    @Override
    public int getAge() {
        return this.age;
    }
    @Override
    public void setDefaultPickUpDelay() {
        this.pickupDelay = 10;
    }
    @Override
    public void setNoPickUpDelay() {
        this.pickupDelay = 0;
    }
    @Override
    public void setNeverPickUp() {
        this.pickupDelay = 32767;
    }
    @Override
    public void setPickUpDelay(int pTicks) {
        this.pickupDelay = pTicks;
    }
    @Override
    public boolean hasPickUpDelay() {
        return this.pickupDelay > 0;
    }
    @Override
    public void setUnlimitedLifetime() {
        this.age = -32768;
    }
    @Override
    public void setExtendedLifetime() {
        this.age = -6000;
    }
    @Override
    public void makeFakeItem() {
        this.setNeverPickUp();
        this.age = getItem().getEntityLifespan(level) - 1;
    }
    @Override
    public float getSpin(float pPartialTicks) {
        return ((float)this.getAge() + pPartialTicks) / 20.0F + this.bobOffs;
    }
    @Override
    public Packet<?> getAddEntityPacket() {
        return new ClientboundAddEntityPacket(this);
    }
    @Override
    public ItemEntity copy() {
        return new CoalSwordEntity(this);
    }
    @Override
    public SoundSource getSoundSource() {
        return SoundSource.AMBIENT;
    }

}

 

Spoiler
public class CoalToolsSword extends SwordItem {


    public CoalToolsSword(Tier pTier, int pAttackDamageModifier, float pAttackSpeedModifier, Properties pProperties) {
        super(pTier, pAttackDamageModifier, pAttackSpeedModifier, pProperties);
    }

    @Override
    public void appendHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltip, TooltipFlag flagIn) {
        if (Screen.hasShiftDown()) {
            tooltip.add(new TextComponent("\u00A7e"+"Thrown into a furnace may have some adverse effects" + "\u00A7e"));
        }
        else {
            tooltip.add(new TextComponent("\u00A77"+"Hold "+"\u00A7e"+"shift "+"\u00A77"+"for more info" + "\u00A77"));
        }
    }

    @Override
    public boolean hasCustomEntity(ItemStack stack) {
        return true;
    }

    @org.jetbrains.annotations.Nullable
    @Override
    public Entity createEntity(Level level, Entity location, ItemStack stack) {
        return new CoalSwordEntity(level, location.getX(), location.getY(), location.getZ(), stack);
    }
}

 

 

Link to comment
Share on other sites

31 minutes ago, diesieben07 said:

Why did you both extend and copy ItemEntity? This does not make any sense.

I extended it originally, but when I added in the code needed, it still didn't function correctly, so I copied it. I will extend Entity instead and see how that pans out

Link to comment
Share on other sites

29 minutes ago, tal124 said:

I extended it originally, but when I added in the code needed, it still didn't function correctly, so I copied it. I will extend Entity instead and see how that pans out

There were a few things I couldn't port over to the copied over code, So I went back to the extending, I'm not sure what code I'm putting in/not putting in thats messing with the ItemEntity and not allowing it to drop.

Link to comment
Share on other sites

15 hours ago, diesieben07 said:

Show updated code. And yes, you should extend it and only override what you need to change.

public class CoalSwordEntity extends ItemEntity {

    public CoalSwordEntity(EntityType<? extends ItemEntity> entityType, Level level) {
        super(entityType, level);
    }

    public CoalSwordEntity(Level level, double x, double y, double z, ItemStack stack) {
        super(level, x, y, z, stack);
    }

    public CoalSwordEntity(Level level, double x, double y, double z, ItemStack stack, double deltaX, double deltaY, double deltaZ) {
        super(level, x, y, z, stack, deltaX, deltaY, deltaZ);
    }

}

I have reverted to what I had originally to try and figure out what the issue was, It not even dropping the item at all, doing the same thing as before, I'm starting to believe my actual issue is somewhere in my ItemClass and not the ItemEntity class

 

Spoiler
@Override
    public boolean hasCustomEntity(ItemStack stack) {
        return true;
    }

    @Nullable
    @Override
    public Entity createEntity(Level level, Entity location, ItemStack stack) {
        return new CoalSwordEntity(level, location.getX(), location.getY(), location.getZ(), stack);
    }

 

Somewhere around here? maybe?

Link to comment
Share on other sites

15 hours ago, Luis_ST said:

you have to create a custom EntityType and you need to register a EntityRenderer for your Entity.

You also can not super the constructor from ItemEntity, since they use the vanilla EntityType 

How do I go about registering the EntityRenderer to the eventbus? I'm a bit stuck on that part as well.

Link to comment
Share on other sites

5 minutes ago, tal124 said:

How do I go about registering the EntityRenderer to the eventbus? I'm a bit stuck on that part as well.

Spoiler
private void DoClientStuff(final FMLClientSetupEvent event) {
        event.enqueueWork(() -> {
            EntityRenderers.register(CoalSwordEntity., CoalSwordRenderer::new);
        });
    }

 

Spoiler
@OnlyIn(Dist.CLIENT)
public class CoalSwordRenderer extends EntityRenderer<CoalSwordEntity> {
    private static final float ITEM_BUNDLE_OFFSET_SCALE = 0.15F;
    private static final int ITEM_COUNT_FOR_5_BUNDLE = 48;
    private static final int ITEM_COUNT_FOR_4_BUNDLE = 32;
    private static final int ITEM_COUNT_FOR_3_BUNDLE = 16;
    private static final int ITEM_COUNT_FOR_2_BUNDLE = 1;
    private static final float FLAT_ITEM_BUNDLE_OFFSET_X = 0.0F;
    private static final float FLAT_ITEM_BUNDLE_OFFSET_Y = 0.0F;
    private static final float FLAT_ITEM_BUNDLE_OFFSET_Z = 0.09375F;
    private final ItemRenderer itemRenderer;
    private final Random random = new Random();

    public CoalSwordRenderer(EntityRendererProvider.Context context) {
        super(context);
        this.itemRenderer = context.getItemRenderer();
        this.shadowRadius = 0.15F;
        this.shadowStrength = 0.75F;
    }

    protected int getRenderAmount(ItemStack pStack) {
        int i = 1;
        if (pStack.getCount() > 48) {
            i = 5;
        } else if (pStack.getCount() > 32) {
            i = 4;
        } else if (pStack.getCount() > 16) {
            i = 3;
        } else if (pStack.getCount() > 1) {
            i = 2;
        }

        return i;
    }

    @Override
    public void render(CoalSwordEntity pEntity, float pEntityYaw, float pPartialTicks, PoseStack pMatrixStack, MultiBufferSource pBuffer, int pPackedLight) {
        pMatrixStack.pushPose();
        ItemStack itemstack = pEntity.getItem();
        int i = itemstack.isEmpty() ? 187 : Item.getId(itemstack.getItem()) + itemstack.getDamageValue();
        this.random.setSeed((long)i);
        BakedModel bakedmodel = this.itemRenderer.getModel(itemstack, pEntity.level, (LivingEntity)null, pEntity.getId());
        boolean flag = bakedmodel.isGui3d();
        int j = this.getRenderAmount(itemstack);
        float f = 0.25F;
        float f1 = Mth.sin(((float)pEntity.getAge() + pPartialTicks) / 10.0F + pEntity.bobOffs) * 0.1F + 0.1F;
        float f2 = shouldBob() ? bakedmodel.getTransforms().getTransform(ItemTransforms.TransformType.GROUND).scale.y() : 0;
        pMatrixStack.translate(0.0D, (double)(f1 + 0.25F * f2), 0.0D);
        float f3 = pEntity.getSpin(pPartialTicks);
        pMatrixStack.mulPose(Vector3f.YP.rotation(f3));
        if (!flag) {
            float f7 = -0.0F * (float)(j - 1) * 0.5F;
            float f8 = -0.0F * (float)(j - 1) * 0.5F;
            float f9 = -0.09375F * (float)(j - 1) * 0.5F;
            pMatrixStack.translate((double)f7, (double)f8, (double)f9);
        }

        for(int k = 0; k < j; ++k) {
            pMatrixStack.pushPose();
            if (k > 0) {
                if (flag) {
                    float f11 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.15F;
                    float f13 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.15F;
                    float f10 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.15F;
                    pMatrixStack.translate(shouldSpreadItems() ? f11 : 0, shouldSpreadItems() ? f13 : 0, shouldSpreadItems() ? f10 : 0);
                } else {
                    float f12 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.15F * 0.5F;
                    float f14 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.15F * 0.5F;
                    pMatrixStack.translate(shouldSpreadItems() ? f12 : 0, shouldSpreadItems() ? f14 : 0, 0.0D);
                }
            }

            this.itemRenderer.render(itemstack, ItemTransforms.TransformType.GROUND, false, pMatrixStack, pBuffer, pPackedLight, OverlayTexture.NO_OVERLAY, bakedmodel);
            pMatrixStack.popPose();
            if (!flag) {
                pMatrixStack.translate(0.0, 0.0, 0.09375F);
            }
        }

        pMatrixStack.popPose();
        super.render(pEntity, pEntityYaw, pPartialTicks, pMatrixStack, pBuffer, pPackedLight);
    }
    @Override
    public ResourceLocation getTextureLocation(CoalSwordEntity pEntity) {
        return TextureAtlas.LOCATION_BLOCKS;
    }

    public boolean shouldSpreadItems() {
        return true;
    }

    public boolean shouldBob() {
        return true;
    }

}

I'm unsure how to actually register it since I can't actually register the ItemEntity as an Entity since that won't accept ItemEntities.

Spoiler
public class ModEntities {

    public static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, CoalTools.MODID);

    //Attaches the deferred register to the event bus
    public static void init() {
        ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus());
    }

    public static final RegistryObject<EntityType<ItemEntity>> COAL_SWORD = ENTITIES.register("coal_sword", () ->
            EntityType.Builder.of(CoalSwordEntity::new, MobCategory.MISC).setShouldReceiveVelocityUpdates(true).build("coal_sword"));

}

 

 

Link to comment
Share on other sites

Whenever I do try and register it, it won't let me 

 

Spoiler
    public static final RegistryObject<EntityType<CoalSwordEntity>> COAL_SWORD_ENTITY = ENTITIES.register("coal_sword", () ->
            EntityType.Builder.of(CoalSwordEntity::new, MobCategory.MISC)
                    .build("coal_sword"));

 

This throws an error of

"no instance(s) of type variable(s) exist so that EntityType<Entity> conforms to EntityType<CoalSwordEntity> inference variable I has incompatible bounds: equality constraints: EntityType<CoalSwordEntity> lower bounds: EntityType<Entity>

Link to comment
Share on other sites

On 3/24/2022 at 8:08 AM, MFMods said:

@tal124  what is it that you are trying to do? because it it's something that can be done in tick handler (update handler), you need none of that above. none.

 

I figured that out when I was working on my ArmorCustomItems, onEntityItemUpdate works fine for it, But now It pops 3 out at once when I drop them in some fire.
 

Spoiler
@Override
    public boolean onEntityItemUpdate(ItemStack stack, ItemEntity entity) {
        if (entity.isOnFire()) {
            entity.remove(Entity.RemovalReason.KILLED);
            entity.spawnAtLocation(ModItems.FIRE_SWORD.get());
        }
        return false;
    }

 

I've gotten it fixed now, this will set the remove the item and spawn the other item that I'm trying to get. I basically discarded the CustomItemEntity because nothing I did with it would work. Once I found the ArmorTick I thought there might be an Entity modifier for it.

Link to comment
Share on other sites

7 hours ago, tal124 said:

But now It pops 3 out at once when I drop them in some fire

yeah.

look - let's say you and me are playing minecraft together now. there are three game instances running: client game on my machine, client game (window with blocky world) on your machine and a server game (doesn't matter on which machine).  and in all three game "programs", there is a sword in fire; you ask  if (entity.isOnFire())  and entity.spawnAtLocation executes three times (although two out of three fire swords are ghosts and you can't pick them up).  you need to ask ( not event.getWorld().isClientSide() and entity.isOnFire() ).

also, if you are handling entity update, ask whether the entity is removed already. if it is, do nothing. i'm not sure if that's still an issue.

Edited by MFMods
Link to comment
Share on other sites

2 hours ago, MFMods said:

yeah.

look - let's say you and me are playing minecraft together now. there are three game instances running: client game on my machine, client game (window with blocky world) on your machine and a server game (doesn't matter on which machine).  and in all three game "programs", there is a sword in fire; you ask  if (entity.isOnFire())  and entity.spawnAtLocation executes three times (although two out of three fire swords are ghosts and you can't pick them up).  you need to ask ( not event.getWorld().isClientSide() and entity.isOnFire() ).

also, if you are handling entity update, ask whether the entity is removed already. if it is, do nothing. i'm not sure if that's still an issue.

Its fixed, I created an Entity.removalReason for the Item and it removes the item before popping out the one Item asked for. The code up there is the current and working version of it. I may go through later and add && level.isClientSide() just for precautions

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.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • rp.crazyheal.xyz mods  
    • I'm developing a dimension, but it's kinda resource intensive so some times during player teleporting it lags behind making the player phase down into the void, so im trying to implement some kind of pregeneration to force the game loading a small set of chunks in the are the player will teleport to. Some of the things i've tried like using ServerLevel and ServerChunkCache methods like getChunk() dont actually trigger chunk generation if the chunk isn't already on persistent storage (already generated) or placing tickets, but that doesn't work either. Ideally i should be able to check when the task has ended too. I've peeked around some pregen engines, but they're too complex for my current understanding of the system of which I have just a basic understanding (how ServerLevel ,ServerChunkCache  and ChunkMap work) of. Any tips or other classes I should be looking into to understand how to do this correctly?
    • https://mclo.gs/4UC49Ao
    • Way back in the Forge 1.17 days, work started for adding JPMS (Java Platform Module Support) to ModLauncher and ForgeModLoader. This has been used internally by Forge and some libraries for a while now, but mods (those with mods.toml specifically) have not been able to take advantage of it. As of Forge 1.21.1 and 1.21.3, this is now possible!   What is JPMS and what does it mean for modders? JPMS is the Java Platform Module System, introduced in Java 9. It allows you to define modules, which are collections of packages and resources that can be exported or hidden from other modules. This allows for much more fine-tuned control over visibility, cleaner syntax for service declarations and support for sealed types across packages. For example, you might have a mod with a module called `com.example.mod` that exports `com.example.mod.api` and `com.example.mod.impl` to other mods, but hides `com.example.mod.internal` from them. This would allow you to have a clean API for other mods to use, while keeping your internal implementation details hidden from IDE hints, helping prevent accidental usage of internals that might break without prior notice. This is particularly useful if you'd like to use public records with module-private constructors or partially module-private record components, as you can create a sealed interface that only your record implements, having the interface be exported and the record hidden. It's also nice for declaring and using services, as you'll get compile-time errors from the Java compiler for typos and the like, rather than deferring to runtime errors. In more advanced cases, you can also have public methods that are only accessible to specific other modules -- handy if you want internal interactions between multiple of your own mods.   How do I bypass it? We understand there may be drama in implementing a system that prevents mods from accessing each other's internals when necessary (like when a mod is abandoned or you need to fix a compat issue) -- after all, we are already modding a game that doesn't have explicit support for Java mods yet. We have already thought of this and are offering APIs from day one to selectively bypass module restrictions. Let me be clear: Forge mods are not required to use JPMS. If you don't want to use it, you don't have to. The default behaviour is to have fully open, fully exported automatic modules. In Java, you can use the `Add-Opens` and `Add-Exports` manifest attributes to selectively bypass module restrictions of other mods at launch time, and we've added explicit support for these when loading your Forge mods. At compile-time, you can use existing solutions such as the extra-java-module-info Gradle plugin to deal with non-modular dependencies and add extra opens and exports to other modules. Here's an example on how to make the internal package `com.example.examplemod.internal` open to your mod in your build.gradle: tasks.named('jar', Jar) { manifest { attributes([ 'Add-Opens' : 'com.example.examplemod/com.example.examplemod.internal' 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors // (...) ]) } } With the above in your mod's jar manifest, you can now reflectively access the classes inside that internal package. Multiple entries are separated with a space, as per Java's official spec. You can also use Add-Exports to directly call without reflection, however you'd need to use the Gradle plugin mentioned earlier to be able to compile. The syntax for Add-Exports is the same as Add-Opens, and instructions for the compile-time step with the Gradle plugin are detailed later in this post. Remember to prefer the opens and exports keywords inside module-info.java for sources you control. The Add-Opens/Add-Exports attributes are only intended for forcing open other mods.   What else is new with module support? Previously, the runtime module name was always forced to the first mod ID in your `mods.toml` file and all packages were forced fully open and exported. Module names are now distinguished from mod IDs, meaning the module name in your module-info.java can be different from the mod ID in your `mods.toml`. This allows you to have a more descriptive module name that doesn't have to be the same as your mod ID, however we strongly recommend including your mod ID as part of your module name to aid troubleshooting. The `Automatic-Module-Name` manifest attribute is now also honoured, allowing you to specify a module name for your mod without needing to create a `module-info.java` file. This is particularly useful for mods that don't care about JPMS features but want to have a more descriptive module name and easier integration with other mods that do use JPMS.   How do I use it? The first step is to create a `module-info.java` file in your mod's source directory. This file should be in the same package as your main mod class, and should look something like this: open module com.example.examplemod { requires net.minecraftforge.eventbus; requires net.minecraftforge.fmlcore; requires net.minecraftforge.forge; requires net.minecraftforge.javafmlmod; requires net.minecraftforge.mergetool.api; requires org.slf4j; requires logging; } For now, we're leaving the whole module open to reflection, which is a good starting point. When we know we want to close something off, we can remove the open modifier from the module and open or export individual packages instead. Remember that you need to be open to Forge (module name net.minecraftforge.forge), otherwise it can't call your mod's constructor. Next is fixing modules in Gradle. While Forge and Java support modules properly, Gradle does not put automatic modules on the module path by default, meaning that the logging module (from com.mojang:logging) is not found. To fix this, add the Gradle plugin and add a compile-time module definition for that Mojang library: plugins { // (...) id 'org.gradlex.extra-java-module-info' version "1.9" } // (...) extraJavaModuleInfo { failOnMissingModuleInfo = false automaticModule("com.mojang:logging", "logging") } The automatic module override specified in your build.gradle should match the runtime one to avoid errors. You can do the same for any library or mod dependency that is missing either a module-info or explicit Automatic-Module-Name, however be aware that you may need to update your mod once said library adds one. That's all you need to get started with module support in your mods. You can learn more about modules and how to use them at dev.java.
    • Faire la mise à jour grâce à ce lien m'a aider personnellement, merci à @Paint_Ninja. https://www.amd.com/en/support 
  • Topics

×
×
  • Create New...

Important Information

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