Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[1.15.2] How do I create an item with power?


TallYate
 Share

Recommended Posts

1 hour ago, Draco18s said:

Capabilities aren't sync'd to the client automatically.

 

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

@Override
	@Nullable
	public CompoundNBT getShareTag(ItemStack stack) {
		CompoundNBT tag = stack.getOrCreateTag();
		stack.getCapability(CapabilityEnergy.ENERGY, null).ifPresent(handler -> {tag.putInt("Energy", stack.getCapability(CapabilityEnergy.ENERGY).orElseGet(null).getEnergyStored());});
		return tag;
	}
	
	@Override
	public void readShareTag(ItemStack stack, @Nullable CompoundNBT nbt)
    {
        stack.setTag(nbt);
        int energy = stack.getCapability(CapabilityEnergy.ENERGY, null).orElse(null).getEnergyStored();
        energy=nbt.getInt("Energy");
    }

I feel like I have done the readShareTag part wrong

Link to comment
Share on other sites

2 hours ago, TallYate said:

ifPresent(handler

handler is your capability instance, you don't need to call getCapability inside here.

2 hours ago, TallYate said:

stack.setTag(nbt);

I don't know why you're doing this.

 

2 hours ago, TallYate said:

stack.getCapability

Use ifPresent

  

2 hours ago, TallYate said:

int energy = ...

energy=nbt.getInt("Energy");

Yes, that's it, just throw the value into a local variable, I'm sure nothing could go wrong.

Edited by Draco18s

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

@Override
	@Nullable
	public CompoundNBT getShareTag(ItemStack stack) {
		CompoundNBT tag = stack.getOrCreateTag();
		stack.getCapability(CapabilityEnergy.ENERGY, null).ifPresent(handler -> {tag.putInt("Energy", handler.getEnergyStored());});
		return tag;
	}
	
	@Override
	public void readShareTag(ItemStack stack, @Nullable CompoundNBT nbt)
    {
        stack.getCapability(CapabilityEnergy.ENERGY, null).ifPresent(handler -> {nbt.putInt("Energy", handler.getEnergyStored());});
    }

ok I've done this.
I did the local variable thing because I thought it was a reference that I could change.
What am I actually supposed to do in readShareTag?

Link to comment
Share on other sites

I'm sure that when you're READING its a great idea to WRITE.

Try READING instead.

Hint, the methods are supposed to be mirrors. In write you get the value FROM the capability, therefor in read you should...

Edited by Draco18s

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

I think I have to do something like
handler.getEnergyStored()=nbt.getInt("Energy");

but getEnergyStored() returns a value and not a variable/reference, and I don't see any other methods to write to the capability.

Edited by TallYate
changed last sentence
Link to comment
Share on other sites

Gosh if there was only some other method that accepted a value instead of returning it.

Hint: You can add one to your implementation, even if it is not specified by the interface

Edited by Draco18s

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

You implemented the interface somewhere, yes?

Use polymorphism to your advantage.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

23 minutes ago, TallYate said:

My Armor Item doesn’t implement IEnergyStorage, I think that came from CapabilityEnergy.ENERGY

Those are two different things. IEnergyStorage is the interface that defines the storage of the data, CapabilityEnergy.ENERGY is the type of capability.

Anyway, the class I was referring to is one that Forge created (EnergyStorage note the lack of an I on the front), I thought they left it for modders to implement, I was wrong.

 

What I'd do, then, is, extract all the energy that the client side capability thinks it has (just dump it on the ground, all we care about is getting the internal value to zero) then inserting the value received from the nbt data.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

Considering that I don't know what you actually did, I have no idea.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

Ok so I saw that <T> is based on the capability so I made a class that is basically the same as CapabilityEnergy
 

public class ModEnergy
{
    @CapabilityInject(ModEnergyStorage.class)
    public static Capability<ModEnergyStorage> ENERGY = null;

    public static void register()
    {
        CapabilityManager.INSTANCE.register(ModEnergyStorage.class, new IStorage<ModEnergyStorage>()
        {
            @Override
            public INBT writeNBT(Capability<ModEnergyStorage> capability, ModEnergyStorage instance, Direction side)
            {
                return IntNBT.valueOf(instance.getEnergyStored());
            }

            @Override
            public void readNBT(Capability<ModEnergyStorage> capability, ModEnergyStorage instance, Direction side, INBT nbt)
            {
                if (!(instance instanceof EnergyStorage))
                    throw new IllegalArgumentException("Can not deserialize to an instance that isn't the default implementation");
                instance.setEnergyStored(((IntNBT)nbt).getInt());
            }
        },
        () -> new ModEnergyStorage(10000, 1000, 1000));
    }
}

but it uses ModEnergyStorage
 

public class ModEnergyStorage extends EnergyStorage{

	public ModEnergyStorage(int capacity, int maxReceive, int maxExtract) {
		super(capacity, maxReceive, maxExtract);
	}
	
    public void setEnergyStored(int x)
    {
        this.energy=x;
    }
	
}

for the extra method
and this is the Item Class

public class PowerArmor extends ArmorItem {
	public PowerArmor(IArmorMaterial materialIn, EquipmentSlotType slot, Properties builder) {
		super(materialIn, slot, builder);
	}

	private ModEnergyStorage newStorage() {
		return new ModEnergyStorage(10000, 1000, 1000);
	}

	@Override
	public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt) {
		return new ICapabilityProvider() {
			protected ModEnergyStorage storage = newStorage();
			protected LazyOptional<ModEnergyStorage> storageHolder = LazyOptional.of(() -> storage);

			public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
				if (cap == ModEnergy.ENERGY) {
					return storageHolder.cast();
				}
				return LazyOptional.empty();
			}
		};
	}

	@Override
	public boolean shouldSyncTag() {
		return true;
	}

	

	@Override
	@Nullable
	public CompoundNBT getShareTag(ItemStack stack) {
		CompoundNBT tag = stack.getOrCreateTag();
		stack.getCapability(ModEnergy.ENERGY, null).ifPresent(handler -> {
			tag.putInt("Energy", handler.getEnergyStored());
			CrudeTechMod.log("getEnergy: " + handler.getEnergyStored());
		});
		return tag;
	}

	@Override
	public void readShareTag(ItemStack stack, @Nullable CompoundNBT nbt) {
		stack.getCapability(ModEnergy.ENERGY, null).ifPresent(handler -> {
			handler.setEnergyStored(nbt.getInt("Energy"));
			CrudeTechMod.log("readEnergy: " + handler.getEnergyStored());
		});

	}

	@Override
	public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip,
			ITooltipFlag flagIn) {
		IEnergyStorage cap = stack.getCapability(ModEnergy.ENERGY, null).orElseGet(null);
		if (cap != null) {
			String charge = Integer.toString(cap.getEnergyStored());
			String capacity = Integer.toString(cap.getMaxEnergyStored());
			tooltip.add(new TranslationTextComponent("Charge: " + charge + "/" + capacity));
		} else {
			tooltip.add(new TranslationTextComponent("missing capability"));
		}
	}
}


 

Link to comment
Share on other sites

10 minutes ago, TallYate said:

if (!(instance instanceof EnergyStorage))

This basically can't happen. ModEnergyStorage extends EnergyStorage, so getting a class that is the former and not the latter is impossible.

13 minutes ago, TallYate said:

CrudeTechMod.log("getEnergy: " + handler.getEnergyStored());

Is this getting called? No?
Have you tried figuring out if the parent method is getting called, but skipping over the lambda?

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

@Override
	@Nullable
	public CompoundNBT getShareTag(ItemStack stack) {
		CompoundNBT tag = stack.getOrCreateTag();
		stack.getCapability(ModCapabilityEnergy.ENERGY, null).ifPresent(handler -> {
			tag.putInt("Energy", handler.getEnergyStored());
			CrudeTechMod.log("getEnergy: " + handler.getEnergyStored());
		});
		CrudeTechMod.log("getShareTag end");
		return tag;
	}

Ok I made the capability more like forges and made a ModIEnergyStorage
now getShareTag is being run, but not readShareTag

Also, getShareTag is getting 0 energy
 

Edited by TallYate
Link to comment
Share on other sites

Your repository is not complete (missing build.gradle), so it cannot be tested by others.

 

getShareTag and readShareTag must be extensions of ItemStack#getTag. Currently your readShareTag does not do that.

Again: read the javadocs, they tell you the use cases that must be supported by your implementation.

Link to comment
Share on other sites

18 minutes ago, TallYate said:

Also, could you link me to the javadocs you're reading?

I can't link to something that is in your IDE.

 

As for your mod... you never put any energy into the thing. So yes it will be 0 always.

But you also never write your capability to the ItemStack, hence it will not persist and cannot ever get to the client (or end up in the share tag). The ICapabilityProvider you attach does not declare that it needs to write NBT data. To do that it must implement INBTSerializable. Forge provides a combination-interface you can use called ICapabilitySerializable.

 

Note also that you won't see readShareTag being called usually when playing single player. This is because vanilla packets aren't actually serialized to bytes when playing single player, they are simply passed through a shared queue between integrated server. Thus the ItemStacks being sent over are not written and then read from NBT, they are simply cloned.

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
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.

 Share




  • Recently Browsing

    No registered users viewing this page.

  • Posts

    • The first one is a vanilla server log. The 2nd one is a debug.log that ends prematurely, because the game could not start, because you started 1.16.5 with Java 17. 1.16.5 requires Java 8.
    • The entity creates a pillar of blocks. It appears to work fine; the blocks are getting placed. But the entity is not rendering. It should be displaying interpolated movement upwards. Instead, the blocks just appear (so the entity is invisible). public void tick() { LogManager.getLogger().info("ticks: " + ticks++ + " current " + blockPosition() + " old " + oldPos); if(blockPosition().equals(endBlockPos)){ if(releaseJutsuOnce != null){ releaseJutsuOnce.execute(); } remove(); return; } if(blockPosition().equals(oldPos.above())){ oldPos = blockPosition(); level.setBlockAndUpdate(blockPosition(), blockState); } setDeltaMovement(0, 0.1, 0); move(MoverType.SELF, getDeltaMovement()); } Renderer (copied from falling block): public class MudWallBlockEntityRenderer extends EntityRenderer<MudWallBlockEntity> { public MudWallBlockEntityRenderer(EntityRendererManager entityRendererManager) { super(entityRendererManager); this.shadowRadius = 0.5F; } @Override public void render(MudWallBlockEntity entity, float entityYaw, float partialTicks, MatrixStack matrixStack, IRenderTypeBuffer buffer, int packedLight) { BlockState blockstate = entity.getBlockState(); if (blockstate.getRenderShape() == BlockRenderType.MODEL) { World world = entity.getCommandSenderWorld(); if (blockstate != world.getBlockState(entity.blockPosition()) && blockstate.getRenderShape() != BlockRenderType.INVISIBLE) { matrixStack.pushPose(); BlockPos blockpos = new BlockPos(entity.getX(), entity.getBoundingBox().maxY, entity.getZ()); matrixStack.translate(-0.5D, 0.0D, -0.5D); BlockRendererDispatcher blockrendererdispatcher = Minecraft.getInstance().getBlockRenderer(); for (net.minecraft.client.renderer.RenderType type : net.minecraft.client.renderer.RenderType.chunkBufferLayers()) { if (RenderTypeLookup.canRenderInLayer(blockstate, type)) { net.minecraftforge.client.ForgeHooksClient.setRenderLayer(type); blockrendererdispatcher.getModelRenderer().tesselateBlock(world, blockrendererdispatcher.getBlockModel(blockstate), blockstate, blockpos, matrixStack, buffer.getBuffer(type), false, new Random(), blockstate.getSeed(entity.getStartingBlockPos()), OverlayTexture.NO_OVERLAY); } } net.minecraftforge.client.ForgeHooksClient.setRenderLayer(null); matrixStack.popPose(); super.render(entity, entityYaw, partialTicks, matrixStack, buffer, packedLight); } } } @Override public ResourceLocation getTextureLocation(MudWallBlockEntity pEntity) { return AtlasTexture.LOCATION_BLOCKS; } } Registration: RenderingRegistry.registerEntityRenderingHandler(ModEntities.MUD_WALL_BLOCK_ENTITY.get(), MudWallBlockEntityRenderer::new);  
    • [04Dec2021 13:01:52.507] [main/INFO] [cpw.mods.modlauncher.Launcher/MODLAUNCHER]: ModLauncher running: args [--gameDir, ., --launchTarget, fmlserver, --fml.forgeVersion, 36.2.19, --fml.mcpVersion, 20210115.111550, --fml.mcVersion, 1.16.5, --fml.forgeGroup, net.minecraftforge, nogui] [04Dec2021 13:01:52.510] [main/INFO] [cpw.mods.modlauncher.Launcher/MODLAUNCHER]: ModLauncher 8.0.9+86+master.3cf110c starting: java version 17.0.1 by Oracle Corporation [04Dec2021 13:01:52.522] [main/DEBUG] [cpw.mods.modlauncher.LaunchServiceHandler/MODLAUNCHER]: Found launch services [minecraft,testharness,fmlclient,fmlserver]   This also might be it?
    • [17:28:20] [main/INFO]: Environment: authHost='https://authserver.mojang.com', accountsHost='https://api.mojang.com', sessionHost='https://sessionserver.mojang.com', servicesHost='https://api.minecraftservices.com', name='PROD' [17:28:20] [main/WARN]: Ambiguity between arguments [teleport, destination] and [teleport, targets] with inputs: [Player, 0123, @e, dd12be42-52a9-4a91-a8a1-11c01849e498] [17:28:20] [main/WARN]: Ambiguity between arguments [teleport, location] and [teleport, destination] with inputs: [0.1 -0.5 .9, 0 0 0] [17:28:20] [main/WARN]: Ambiguity between arguments [teleport, location] and [teleport, targets] with inputs: [0.1 -0.5 .9, 0 0 0] [17:28:20] [main/WARN]: Ambiguity between arguments [teleport, targets] and [teleport, destination] with inputs: [Player, 0123, dd12be42-52a9-4a91-a8a1-11c01849e498] [17:28:20] [main/WARN]: Ambiguity between arguments [teleport, targets, location] and [teleport, targets, destination] with inputs: [0.1 -0.5 .9, 0 0 0] [17:28:20] [main/INFO]: Reloading ResourceManager: Default [17:28:21] [Worker-Main-10/INFO]: Loaded 7 recipes [17:28:22] [Worker-Main-10/INFO]: Loaded 927 advancements [17:28:24] [Server thread/INFO]: Starting minecraft server version 1.16.5 [17:28:24] [Server thread/INFO]: Loading properties [17:28:24] [Server thread/INFO]: Default game type: SURVIVAL [17:28:24] [Server thread/INFO]: Generating keypair [17:28:24] [Server console handler/ERROR]: Exception handling console input java.io.IOException: The handle is invalid     at java.io.FileInputStream.readBytes(Native Method) ~[?:?]     at java.io.FileInputStream.read(FileInputStream.java:276) ~[?:?]     at java.io.BufferedInputStream.read1(BufferedInputStream.java:282) ~[?:?]     at java.io.BufferedInputStream.read(BufferedInputStream.java:343) ~[?:?]     at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:270) ~[?:?]     at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:313) ~[?:?]     at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:188) ~[?:?]     at java.io.InputStreamReader.read(InputStreamReader.java:177) ~[?:?]     at java.io.BufferedReader.fill(BufferedReader.java:162) ~[?:?]     at java.io.BufferedReader.readLine(BufferedReader.java:329) ~[?:?]     at java.io.BufferedReader.readLine(BufferedReader.java:396) ~[?:?]     at zg$1.run(SourceFile:95) [server.jar.jar:?] [17:28:24] [Server thread/INFO]: Starting Minecraft server on *:25565 [17:28:24] [Server thread/INFO]: Using default channel type [17:28:25] [Server thread/WARN]: Failed to load white-list:  com.google.gson.JsonSyntaxException: Expected entry to be a JsonObject, was "Sta...ne"     at afd.m(SourceFile:393) ~[server.jar.jar:?]     at acy.f(SourceFile:122) ~[server.jar.jar:?]     at zf.B(SourceFile:119) ~[server.jar.jar:?]     at zf.<init>(SourceFile:27) ~[server.jar.jar:?]     at zg.d(SourceFile:169) ~[server.jar.jar:?]     at net.minecraft.server.MinecraftServer.w(SourceFile:645) ~[server.jar.jar:?]     at net.minecraft.server.MinecraftServer.a(SourceFile:257) ~[server.jar.jar:?]     at java.lang.Thread.run(Thread.java:833) [?:?] [17:28:25] [Server thread/INFO]: Preparing level "Better Minecraft" [17:28:25] [Server thread/INFO]: Preparing start region for dimension minecraft:overworld [17:28:27] [Server thread/INFO]: Preparing spawn area: 0% [17:28:27] [Server thread/INFO]: Preparing spawn area: 0% [17:28:27] [Server thread/INFO]: Preparing spawn area: 0% [17:28:27] [Server thread/INFO]: Preparing spawn area: 0% [17:28:28] [Server thread/INFO]: Preparing spawn area: 0% [17:28:28] [Server thread/INFO]: Preparing spawn area: 47% [17:28:32] [Worker-Main-9/INFO]: Preparing spawn area: 83% [17:28:32] [Worker-Main-9/INFO]: Preparing spawn area: 83% [17:28:32] [Worker-Main-8/INFO]: Preparing spawn area: 83% [17:28:32] [Worker-Main-9/INFO]: Preparing spawn area: 83% [17:28:32] [Worker-Main-9/INFO]: Preparing spawn area: 83% [17:28:32] [Worker-Main-9/INFO]: Preparing spawn area: 83% [17:28:32] [Worker-Main-9/INFO]: Preparing spawn area: 83% [17:28:32] [Worker-Main-7/INFO]: Preparing spawn area: 83% [17:28:32] [Worker-Main-9/INFO]: Preparing spawn area: 83% [17:28:33] [Worker-Main-9/INFO]: Preparing spawn area: 83% [17:28:33] [Worker-Main-8/INFO]: Preparing spawn area: 83% [17:28:34] [Worker-Main-7/INFO]: Preparing spawn area: 83% [17:28:34] [Worker-Main-9/INFO]: Preparing spawn area: 83% [17:28:35] [Worker-Main-9/INFO]: Preparing spawn area: 84% [17:28:35] [Worker-Main-6/INFO]: Preparing spawn area: 84% [17:28:36] [Server thread/INFO]: Preparing spawn area: 89% [17:28:36] [Server thread/INFO]: Time elapsed: 10908 ms [17:28:36] [Server thread/INFO]: Done (11.035s)! For help, type "help" [17:30:38] [User Authenticator #1/INFO]: UUID of player Stark3rmine is c3b23361-12df-4ef7-81f5-a0c864d1bf3c [17:30:38] [Server thread/INFO]: Stark3rmine[/127.0.0.1:65426] logged in with entity id 170 at (178.5, 74.0, 249.5) [17:30:38] [Server thread/INFO]: Stark3rmine joined the game [17:30:41] [Server thread/INFO]: Stark3rmine lost connection: Disconnected [17:30:41] [Server thread/INFO]: Stark3rmine left the game [17:30:45] [User Authenticator #2/INFO]: UUID of player Stark3rmine is c3b23361-12df-4ef7-81f5-a0c864d1bf3c [17:30:45] [Server thread/INFO]: Stark3rmine[/127.0.0.1:65431] logged in with entity id 172 at (178.5, 74.0, 249.5) [17:30:45] [Server thread/INFO]: Stark3rmine joined the game [17:30:47] [Server thread/INFO]: Stark3rmine lost connection: Disconnected [17:30:47] [Server thread/INFO]: Stark3rmine left the game   This?
    • It worked thanks a lot ❤️ I'm gonna paste all of my code for anyone in the future looking to do capabilities package com.chickenwand3.rpgmod.core.capabilities.entity; import javax.annotation.Nullable; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.capabilities.CapabilityToken; import net.minecraftforge.common.capabilities.ICapabilityProvider; public class CapabilityMobLevel{ public static Capability<MobLevel> MOB_LEVEL_CAPABILITY = CapabilityManager.get(new CapabilityToken<>() {}); public static void register() { CapabilityManager.INSTANCE.register(MobLevel.class); } } package com.chickenwand3.rpgmod.core.capabilities.entity; public class DefaultMobLevel implements MobLevel { public int mobLevel; public float mobMaxHealth; public float mobCurrentHealth; public boolean crazy; public boolean isCrazy() { return crazy; } public float getMaxHealth() { return mobMaxHealth; } public float getCurrentHealth() { return mobCurrentHealth; } } package com.chickenwand3.rpgmod.core.capabilities.entity; public interface MobLevel { } package com.chickenwand3.rpgmod.core.capabilities.entity; import com.chickenwand3.rpgmod.RPGMod; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Animal; import net.minecraft.world.entity.monster.Zombie; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; @Mod.EventBusSubscriber(modid = RPGMod.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE) public class MobLevelEventHandler { @SubscribeEvent public static void onAttachCapabilitiesEvent(AttachCapabilitiesEvent<Entity> event) { if (event.getObject() instanceof Mob && !event.getObject().getCommandSenderWorld().isClientSide) { MobLevelProvider providerMobLevel = new MobLevelProvider(); event.addCapability(new ResourceLocation(RPGMod.MODID, "moblevel"), providerMobLevel); event.addListener(providerMobLevel::invalidate); } } @SubscribeEvent public void registerCaps(RegisterCapabilitiesEvent event) { event.register(MobLevel.class); } @SubscribeEvent public static void OnSpawn(final EntityJoinWorldEvent event) { if (event.getEntity()instanceof Mob target && !event.getWorld().isClientSide) { target.getCapability(CapabilityMobLevel.MOB_LEVEL_CAPABILITY).ifPresent(mobLevel -> { DefaultMobLevel actualMobLevel = (DefaultMobLevel) mobLevel; if (actualMobLevel.mobLevel < 1) { actualMobLevel.mobLevel = (randomizeMobLevel()); } if (superCrazy(actualMobLevel.mobLevel)) { actualMobLevel.crazy = true; } if (actualMobLevel.crazy) { if (!target.getMainHandItem().isEmpty()) { target.getMainHandItem().enchant(Enchantments.FIRE_ASPECT, 1); } if (event.getEntity()instanceof Zombie zombie) { zombie.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).setBaseValue(0.99D); } System.out.println("Super Crazy " + target.getName() + " has spawned!"); } actualMobLevel.mobMaxHealth = (target.getMaxHealth() * actualMobLevel.mobLevel * 2); actualMobLevel.mobCurrentHealth = actualMobLevel.mobMaxHealth; target.getAttribute(Attributes.MOVEMENT_SPEED) .setBaseValue(target.getAttributeValue(Attributes.MOVEMENT_SPEED) * (1 + (actualMobLevel.mobLevel - 1.0) / 10.0)); if (target.getAttribute(Attributes.ATTACK_DAMAGE) != null) { target.getAttribute(Attributes.ATTACK_DAMAGE) .setBaseValue(target.getAttributeValue(Attributes.ATTACK_DAMAGE) * (1 + (actualMobLevel.mobLevel - 1.0) / 2.0)); } }); } } private static int randomizeMobLevel() { boolean roll = true; int level = 1; while (roll) { if (Math.random() > .5) { level += 1; roll = true; } else { roll = false; } } return level; } private static boolean superCrazy(int level) { boolean result = false; if (level >= 5) { if (Math.random() < .25) { result = true; } else result = false; } return result; } } package com.chickenwand3.rpgmod.core.capabilities.entity; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.util.LazyOptional; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class MobLevelProvider implements ICapabilitySerializable<CompoundTag> { private final DefaultMobLevel mobLevel = new DefaultMobLevel(); private final LazyOptional<MobLevel> mobLevelOptional = LazyOptional.of(() -> mobLevel); public void invalidate() { mobLevelOptional.invalidate(); } @Nonnull @Override public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { return mobLevelOptional.cast(); } @Override public CompoundTag serializeNBT() { System.out.println("It serialized"); if (CapabilityMobLevel.MOB_LEVEL_CAPABILITY == null) { System.out.println("It made a new compound"); return new CompoundTag(); } else { System.out.println("It serialized the values"); CompoundTag compoundNBT = new CompoundTag(); compoundNBT.putInt("mobLevel", mobLevel.mobLevel); compoundNBT.putFloat("mobCurrentHealth", mobLevel.mobCurrentHealth); compoundNBT.putFloat("mobMaxHealth", mobLevel.mobMaxHealth); compoundNBT.putBoolean("crazy", mobLevel.crazy); return compoundNBT; } } @Override public void deserializeNBT(CompoundTag nbt) { System.out.println("It deserialized"); if (CapabilityMobLevel.MOB_LEVEL_CAPABILITY != null) { System.out.println("It deserialized the values"); mobLevel.mobLevel = (nbt.getInt("mobLevel")); float mobCurrentHealth = nbt.getFloat("mobCurrentHealth"); mobLevel.mobCurrentHealth = (mobCurrentHealth); float mobMaxHealth = nbt.getFloat("mobMaxHealth"); mobLevel.mobMaxHealth = (mobMaxHealth); boolean crazy = nbt.getBoolean("crazy"); mobLevel.crazy = (crazy); } } }  
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.