Jump to content

How would one go about registering custom attributes?


Ninjaguy169

Recommended Posts

Registry Class:

 

	public static final DeferredRegister<Attribute> ATTRIBUTES = DeferredRegister.create(ForgeRegistries.ATTRIBUTES, ReachMod.MODID);
	
	//ATTRIBUTES
	public static final RegistryObject<Attribute> ATTACK_REACH = ATTRIBUTES.register("attack_reach", () -> (Attribute) new RangedAttribute("attribute.mod.attack_reach", 5.0D, 0.0D, 1024.0D).setSyncable(true));
	
	//MODIFIERS
	public static final UUID ATTACH_REACH_MODIFIER = UUID.fromString("7cc9a781-fdde-4e1b-85fe-acb912fc0430");

 

Main Class:

 

//Register stuff
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();

ModAttributes.ATTRIBUTES.register(bus);

 

Extra stuff (events):

 

    @EventBusSubscriber(bus = Bus.MOD)
    public static class ClientHelper{ 
        @SuppressWarnings("unused")
    	private static RayTraceResult getEntityMouseOverExtended(float reach) {
            BlockRayTraceResult blockRayTraceResult = null;
            RayTraceResult result = null;
            Minecraft mc = Minecraft.getInstance();
            Entity viewEntity = mc.crosshairPickEntity;
            PlayerController p = mc.gameMode;
            if (viewEntity != null) {
              double d0 = reach;
              RayTraceResult rayTrace = viewEntity.pick(d0, 0.0F, false);
              Vector3d eyePos = viewEntity.getEyePosition(0.0F);
              boolean flag = false;
              double d1 = d0;
              if (p.hasFarPickRange() && d1 < 6.0D) {
                d1 = 6.0D;
                d0 = d1;
              } else if (d0 > reach) {
                flag = true;
              } 
              d1 *= d1;
              if (rayTrace != null)
                d1 = rayTrace.getLocation().distanceToSqr(eyePos); 
              Vector3d lookVec = viewEntity.getEyePosition(1.0F);
              Vector3d attackVec = eyePos.add(lookVec.x * d0, lookVec.y * d0, lookVec.z * d0);
              AxisAlignedBB expBounds = viewEntity.getBoundingBox().expandTowards(lookVec.scale(d0)).inflate(1.0D, 1.0D, 1.0D);
              EntityRayTraceResult entityRayTrace = ProjectileHelper.getEntityHitResult(viewEntity, eyePos, attackVec, expBounds, entity -> 
                  
                  (!entity.isSpectator() && entity.canBeCollidedWith()), d1);
              if (entityRayTrace != null) {
                Vector3d hitVec = entityRayTrace.getLocation();
                double d2 = eyePos.distanceToSqr(hitVec);
                if (flag && d2 > (reach * reach)) {
                  blockRayTraceResult = BlockRayTraceResult.miss(hitVec, Direction.getNearest(lookVec.x, lookVec.y, lookVec.z), new BlockPos(hitVec));
                } else if (d2 < d1 || blockRayTraceResult == null) {
                  EntityRayTraceResult entityRayTraceResult = entityRayTrace;
                } 
              } else {
                blockRayTraceResult = BlockRayTraceResult.miss(attackVec, Direction.getNearest(lookVec.x, lookVec.y, lookVec.z), new BlockPos(attackVec));
              } 
            } 
            return (RayTraceResult)blockRayTraceResult;
          }
        
        private static void checkForReachAttack() {
            Minecraft mc = Minecraft.getInstance();
            ClientPlayerEntity clientPlayerEntity = mc.player;
            if (clientPlayerEntity == null || clientPlayerEntity.isSpectator())
              return; 
            double reach = (float)clientPlayerEntity.getAttributeValue(ModAttributes.ATTACK_REACH.get());
            if (reach == ModAttributes.ATTACK_REACH.get().getDefaultValue())
              return; 
            RayTraceResult rayTrace = getEntityMouseOverExtended((float)reach);
            if (!(rayTrace instanceof EntityRayTraceResult))
              return; 
            EntityRayTraceResult entityRayTrace = (EntityRayTraceResult)rayTrace;
            Entity entityHit = entityRayTrace.getEntity();
            if (entityHit != null && entityHit.invulnerableTime == 0 && entityHit != clientPlayerEntity && entityHit != clientPlayerEntity.getControllingPassenger()) {
              float velocity = 0.0F;
              if (clientPlayerEntity.getControllingPassenger() != null) {
                Entity riding = clientPlayerEntity.getControllingPassenger();
                Vector3d vec = riding.getDeltaMovement();
                velocity = (float)vec.length();
              } 
              PacketHandler.sendPacketToServer(new PacketReach(velocity, entityHit.getId()));
            } 
          }

        @SubscribeEvent(priority = EventPriority.NORMAL, receiveCanceled = true)
        @SuppressWarnings("resource")
    	public static void mouseEvent(InputEvent.MouseInputEvent event) {
            if (Minecraft.getInstance().level == null || Minecraft.getInstance().screen == null || Minecraft.getInstance().isPaused())
                return; 
              KeyBinding keyAttack = Minecraft.getInstance().options.keyAttack;
              if (event.getButton() == keyAttack.getKey().getValue() && event.getAction() == 1 && ModAttributes.ATTACK_REACH.isPresent())
                checkForReachAttack(); 
        }
}

 

All I need is to register the events and my registries to the mod event bus, right?

Edited by Ninjaguy169
Link to comment
Share on other sites

7 minutes ago, Ninjaguy169 said:

All I need is to register the events and my registries to the mod event bus, right?

InputEvent.MouseInputEvent is a Forge Bus Event, only the registry Events are Mod Bus Events (all Events which implements IModBusEvent)

Link to comment
Share on other sites

Description: Unexpected error

java.lang.IllegalArgumentException: Can't find attribute reachmod:attack_reach
	at net.minecraft.entity.ai.attributes.AttributeModifierMap.getAttributeInstance(AttributeModifierMap.java:21) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading}
	at net.minecraft.entity.ai.attributes.AttributeModifierMap.getValue(AttributeModifierMap.java:28) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading}
	at net.minecraft.entity.ai.attributes.AttributeModifierManager.getValue(AttributeModifierManager.java:62) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading}
	at net.minecraft.entity.LivingEntity.getAttributeValue(LivingEntity.java:1731) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:accesstransformer:B,re:mixin,pl:accesstransformer:B}
	at com.creator.reachmod.client.ClientEvent$ReachClientHelper.checkForReachAttack(ClientEvent.java:105) ~[main/:?] {re:classloading}
	at com.creator.reachmod.client.ClientEventEvent$ReachClientHelper.mouseEvent(ClientEvent.java:131) ~[main/:?] {re:classloading}
	at net.minecraftforge.eventbus.ASMEventHandler_60_ReachClientHelper_mouseEvent_MouseInputEvent.invoke(.dynamic) ~[?:?] {}
	at net.minecraftforge.eventbus.ASMEventHandler.invoke(ASMEventHandler.java:85) ~[eventbus-4.0.0.jar:?] {}
	at net.minecraftforge.eventbus.EventBus.post(EventBus.java:302) ~[eventbus-4.0.0.jar:?] {}
	at net.minecraftforge.eventbus.EventBus.post(EventBus.java:283) ~[eventbus-4.0.0.jar:?] {}
	at net.minecraftforge.client.ForgeHooksClient.fireMouseInput(ForgeHooksClient.java:811) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading}
	at net.minecraft.client.MouseHelper.onPress(MouseHelper.java:118) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A}
	at net.minecraft.client.MouseHelper.lambda$null$4(MouseHelper.java:181) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A}
	at net.minecraft.util.concurrent.ThreadTaskExecutor.execute(ThreadTaskExecutor.java:94) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:accesstransformer:B,re:mixin,pl:accesstransformer:B}
	at net.minecraft.client.MouseHelper.lambda$setup$5(MouseHelper.java:180) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A}
	at org.lwjgl.glfw.GLFWMouseButtonCallbackI.callback(GLFWMouseButtonCallbackI.java:36) ~[lwjgl-glfw-3.2.2.jar:build 10] {}
	at org.lwjgl.system.JNI.invokeV(Native Method) ~[lwjgl-3.2.2.jar:build 10] {}
	at org.lwjgl.glfw.GLFW.glfwPollEvents(GLFW.java:3101) ~[lwjgl-glfw-3.2.2.jar:build 10] {}
	at com.mojang.blaze3d.systems.RenderSystem.flipFrame(RenderSystem.java:102) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A}
	at net.minecraft.client.MainWindow.updateDisplay(MainWindow.java:306) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A}
	at net.minecraft.client.Minecraft.runTick(Minecraft.java:997) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:accesstransformer:B,pl:runtimedistcleaner:A,re:mixin,pl:accesstransformer:B,pl:runtimedistcleaner:A}
	at net.minecraft.client.Minecraft.run(Minecraft.java:607) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:accesstransformer:B,pl:runtimedistcleaner:A,re:mixin,pl:accesstransformer:B,pl:runtimedistcleaner:A}
	at net.minecraft.client.main.Main.main(Main.java:184) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A}
	at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?] {}
	at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?] {}
	at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?] {}
	at java.lang.reflect.Method.invoke(Method.java:568) ~[?:?] {}
	at net.minecraftforge.userdev.FMLUserdevClientLaunchProvider.lambda$launchService$0(FMLUserdevClientLaunchProvider.java:52) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {}
	at cpw.mods.modlauncher.LaunchServiceHandlerDecorator.launch(LaunchServiceHandlerDecorator.java:37) [modlauncher-8.1.3.jar:?] {}
	at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:54) [modlauncher-8.1.3.jar:?] {}
	at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:72) [modlauncher-8.1.3.jar:?] {}
	at cpw.mods.modlauncher.Launcher.run(Launcher.java:82) [modlauncher-8.1.3.jar:?] {}
	at cpw.mods.modlauncher.Launcher.main(Launcher.java:66) [modlauncher-8.1.3.jar:?] {}
	at net.minecraftforge.userdev.LaunchTesting.main(LaunchTesting.java:108) [forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {}


A detailed walkthrough of the error, its code path and all known details is as follows:
---------------------------------------------------------------------------------------

-- Head --
Thread: Render thread
Stacktrace:
	at net.minecraft.entity.ai.attributes.AttributeModifierMap.getAttributeInstance(AttributeModifierMap.java:21) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading}
	at net.minecraft.entity.ai.attributes.AttributeModifierMap.getValue(AttributeModifierMap.java:28) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading}
	at net.minecraft.entity.ai.attributes.AttributeModifierManager.getValue(AttributeModifierManager.java:62) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading}
	at net.minecraft.entity.LivingEntity.getAttributeValue(LivingEntity.java:1731) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:accesstransformer:B,re:mixin,pl:accesstransformer:B}
	at com.creator.reachmod.client.ClientEvent$ReachClientHelper.checkForReachAttack(ClientEvent.java:105) ~[main/:?] {re:classloading}
	at com.creator.reachmod.client.ClientEvent$ReachClientHelper.mouseEvent(ClientEvent.java:131) ~[main/:?] {re:classloading}
	at net.minecraftforge.eventbus.ASMEventHandler_60_ReachClientHelper_mouseEvent_MouseInputEvent.invoke(.dynamic) ~[?:?] {}
	at net.minecraftforge.eventbus.ASMEventHandler.invoke(ASMEventHandler.java:85) ~[eventbus-4.0.0.jar:?] {}
	at net.minecraftforge.eventbus.EventBus.post(EventBus.java:302) ~[eventbus-4.0.0.jar:?] {}
	at net.minecraftforge.eventbus.EventBus.post(EventBus.java:283) ~[eventbus-4.0.0.jar:?] {}
	at net.minecraftforge.client.ForgeHooksClient.fireMouseInput(ForgeHooksClient.java:811) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading}
	at net.minecraft.client.MouseHelper.onPress(MouseHelper.java:118) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A}
	at net.minecraft.client.MouseHelper.lambda$null$4(MouseHelper.java:181) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A}
	at net.minecraft.util.concurrent.ThreadTaskExecutor.execute(ThreadTaskExecutor.java:94) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:accesstransformer:B,re:mixin,pl:accesstransformer:B}
	at net.minecraft.client.MouseHelper.lambda$setup$5(MouseHelper.java:180) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A}
	at org.lwjgl.glfw.GLFWMouseButtonCallbackI.callback(GLFWMouseButtonCallbackI.java:36) ~[lwjgl-glfw-3.2.2.jar:build 10] {}
	at org.lwjgl.system.JNI.invokeV(Native Method) ~[lwjgl-3.2.2.jar:build 10] {}
	at org.lwjgl.glfw.GLFW.glfwPollEvents(GLFW.java:3101) ~[lwjgl-glfw-3.2.2.jar:build 10] {}
	at com.mojang.blaze3d.systems.RenderSystem.flipFrame(RenderSystem.java:102) ~[forge:?] {re:classloading,pl:runtimedistcleaner:A}
-- Affected level --
Details:
	All players: 1 total; [ClientPlayerEntity['Dev'/407, l='ClientLevel', x=107.50, y=84.00, z=-191.50]]
	Chunk stats: Client Chunk Cache: 841, 529
	Level dimension: minecraft:overworld
	Level spawn location: World: (112,78,-192), Chunk: (at 0,4,0 in 7,-12; contains blocks 112,0,-192 to 127,255,-177), Region: (0,-1; contains chunks 0,-32 to 31,-1, blocks 0,0,-512 to 511,255,-1)
	Level time: 179 game time, 179 day time
	Server brand: forge
	Server type: Integrated singleplayer server
Stacktrace:
	at net.minecraft.client.world.ClientWorld.fillReportDetails(ClientWorld.java:447) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A,re:mixin,pl:runtimedistcleaner:A}
	at net.minecraft.client.Minecraft.fillReport(Minecraft.java:2031) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:accesstransformer:B,pl:runtimedistcleaner:A,re:mixin,pl:accesstransformer:B,pl:runtimedistcleaner:A}
	at net.minecraft.client.Minecraft.run(Minecraft.java:628) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:accesstransformer:B,pl:runtimedistcleaner:A,re:mixin,pl:accesstransformer:B,pl:runtimedistcleaner:A}
	at net.minecraft.client.main.Main.main(Main.java:184) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {re:classloading,pl:runtimedistcleaner:A}
	at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?] {}
	at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?] {}
	at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?] {}
	at java.lang.reflect.Method.invoke(Method.java:568) ~[?:?] {}
	at net.minecraftforge.userdev.FMLUserdevClientLaunchProvider.lambda$launchService$0(FMLUserdevClientLaunchProvider.java:52) ~[forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {}
	at cpw.mods.modlauncher.LaunchServiceHandlerDecorator.launch(LaunchServiceHandlerDecorator.java:37) [modlauncher-8.1.3.jar:?] {}
	at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:54) [modlauncher-8.1.3.jar:?] {}
	at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:72) [modlauncher-8.1.3.jar:?] {}
	at cpw.mods.modlauncher.Launcher.run(Launcher.java:82) [modlauncher-8.1.3.jar:?] {}
	at cpw.mods.modlauncher.Launcher.main(Launcher.java:66) [modlauncher-8.1.3.jar:?] {}
	at net.minecraftforge.userdev.LaunchTesting.main(LaunchTesting.java:108) [forge-1.16.5-36.2.33_mapped_official_1.16.5.jar:?] {}

 

Edited by Ninjaguy169
Link to comment
Share on other sites

EntityAttributeModificationEvent:

 

    @SubscribeEvent
    public static void onEntityAttributeModificationEvent(final EntityAttributeModificationEvent event) {
		event.add(EntityType.PLAYER, ForgeMod.REACH_DISTANCE.get());
	}

 

Test Weapon Item:

 

    protected static final UUID ATTACK_KNOCKBACK_MODIFIER = UUID.fromString("C59EC38E-DC43-11EB-BA80-0242AC130004");
    public static final UUID REACH_MODIFIER = UUID.fromString("5C05J864-4748-24CE-90D6-0242AC170006");
    private final Multimap<Attribute, AttributeModifier> attributeModifiers;
    public AnimationFactory factory = new AnimationFactory(this);

    public TestItem(IItemTier t, int dmg, float speed, double reachDistance, double knockBack, Properties prop) {
        super(t, dmg, speed, prop);
        float attackDamage = (float) dmg + t.getAttackDamageBonus();
        ImmutableMultimap.Builder<Attribute, AttributeModifier> builder = ImmutableMultimap.builder();
        builder.put(Attributes.ATTACK_DAMAGE, new AttributeModifier(BASE_ATTACK_DAMAGE_UUID, "Weapon modifier", dmg, AttributeModifier.Operation.ADDITION));
        builder.put(Attributes.ATTACK_SPEED, new AttributeModifier(BASE_ATTACK_SPEED_UUID, "Weapon modifier", speed, AttributeModifier.Operation.ADDITION));

        ForgeMod.getInstance();
        if (ForgeMod.REACH_DISTANCE.isPresent()) {
        	builder.put(ForgeMod.REACH_DISTANCE.get(), new AttributeModifier(REACH_MODIFIER, "Weapon modifier", reachDistance, AttributeModifier.Operation.ADDITION));
        }
		
        builder.put(Attributes.ATTACK_KNOCKBACK, new AttributeModifier(ATTACK_KNOCKBACK_MODIFIER, "Weapon modifier", knockBack, AttributeModifier.Operation.ADDITION));
        this.attributeModifiers = builder.build();
    }
      
    @Override
    public Multimap<Attribute, AttributeModifier> getDefaultAttributeModifiers(EquipmentSlotType equipmentSlot) {
        return equipmentSlot == EquipmentSlotType.MAINHAND ? this.attributeModifiers : super.getDefaultAttributeModifiers(equipmentSlot);
    }

 

Registry Item:

 

    public static final RegistryObject<TestItem> TEST_ITEM = ITEMS.register("test_item", () -> new TestItem(ModItemTiers.TEST, 100, -3.2F, 15F, 0, new Item.Properties().rarity(Rarity.EPIC).tab(ModItemGroups.EQUIPMENT)));

 

Pretty sure I need to do something else, although I just can't seem to lay my finger on it.

Edited by Ninjaguy169
Link to comment
Share on other sites

I haven't really worked with lazily initialized stuff before, but so far I've created:

 

 public static final Lazy<Multimap<Attribute, AttributeModifier>> LAZY = Lazy.of(() -> modifierMap);

 

Forgive me for acting dumb, but may I get a bit more clarity on what to do?

 

Edit: So for the method "getAttributeModifiers(EquipmentSlotType slot, ItemStack stack)", I'd just return 

return slot == EquipmentSlotType.MAINHAND ? LAZY.get() : super.getAttributeModifiers(slot, stack);

 

is that right?

Edited by Ninjaguy169
Link to comment
Share on other sites

Ah alr, so a lambda?

    public final Lazy<Multimap<Attribute, AttributeModifier>> LAZY = Lazy.of(() ->  {    
      //Create a new MultiMap using ArrayListMultiMap.create(), probably not make it null
    	Multimap<Attribute, AttributeModifier> attributeModifiers = null;
    	return attributeModifiers;
    });

 

Then I would go about, modifying it inside the "getAttributeValue" method, or is there something else I need to do?

 

Edited by Ninjaguy169
Link to comment
Share on other sites

So,

    public final Lazy<Multimap<Attribute, AttributeModifier>> LAZY = Lazy.of(() ->  {    
    	ImmutableMultimap.Builder<Attribute, AttributeModifier> builder = ImmutableMultimap.builder(); 
    	 builder.put(Attributes.ATTACK_DAMAGE, new AttributeModifier(BASE_ATTACK_DAMAGE_UUID, "Weapon modifier", damage, AttributeModifier.Operation.ADDITION));
         builder.put(Attributes.ATTACK_SPEED, new AttributeModifier(BASE_ATTACK_SPEED_UUID, "Weapon modifier", speed, AttributeModifier.Operation.ADDITION));
         
         if (ForgeMod.REACH_DISTANCE.isPresent()) {
             builder.put(ForgeMod.REACH_DISTANCE.get(), new AttributeModifier(ATTACK_REACH_MODIFIER, "Weapon modifier", reach, AttributeModifier.Operation.ADDITION));
         }
         builder.put(Attributes.ATTACK_KNOCKBACK, new AttributeModifier(ATTACK_KNOCKBACK_MODIFIER, "Weapon modifier", kb, AttributeModifier.Operation.ADDITION));
    	Multimap<Attribute, AttributeModifier> attributeModifiers = ArrayListMultimap.create();
    	attributeModifiers = builder.build();
    	return attributeModifiers;
    });

 

Then I set the new value in the EntityAttributeModificationEvent to whatever static int I have in the item's class?

 

EDIT: I finally got it to work after adding all the values inside the map as you told me to. Thanks a bunch.

Edited by Ninjaguy169
Link to comment
Share on other sites

50 minutes ago, Ninjaguy169 said:
    	Multimap<Attribute, AttributeModifier> attributeModifiers = ArrayListMultimap.create();
    	attributeModifiers = builder.build();

this is completely unnecessary, why did you not return ImmutableMultimap.Builder#build

Edited by Luis_ST
Link to comment
Share on other sites

  • 1 month later...
12 hours ago, Sokoly_ said:

Hello, I also want to increase the reach attack of some tools.

then read the posts before there is a solution

 

12 hours ago, Sokoly_ said:

I would like you to help me especially with the PacketHandler and put it in the tools

what did you mean by "PacketHandler and put it in the tools"?

Link to comment
Share on other sites

  • 2 months later...

Woah, this is pretty old and it hasn't been closed, so I may as well shove my solution in here.

 

You instantiate a new Lazy, create a new 

ImmutableMultimap.Builder<Attribute, AttributeModifier>

, shove your attributes alongside their modified values into that map, and return that map inside the Lazy.

 

Afterwards (this is what I personally did), override the 'onEntitySwing' method in your item class. Get the player's eye position and check where they're looking. Get the distance (squared) between the attacker and the target. If the distance is close enough to where you can reach the target with your weapon/item, hurt the target.

 

I feel like my explanation isn't that clear, so to make up for my lack of better wording, I made an example item class for anyone reading to follow:

 

public class ExampleReachItem extends SwordItem {
    public static final UUID REACH_MOD = UUID.fromString("dccd59ec-6391-436d-9e00-47f2e6005e20"); //A randomly generated version 4 UUID
    public static final UUID KNOCKBACK_MOD = UUID.fromString("15bf6a06-b73b-4d8e-946a-61f63e1ba01e"); //Another randomly generated version 4 UUID
    public static double reach;
    public static double knockBack;
    public static int damage;
    public static int attackSpd;
    public static Lazy<? extends Multimap<Attribute, AttributeModifier>> ATTRIBUTE_LAZY_MAP = Lazy.of(() -> {
        Multimap<Attribute, AttributeModifier> map;
        ImmutableMultimap.Builder<Attribute, AttributeModifier> builder = ImmutableMultimap.builder();
        builder.put(Attributes.ATTACK_DAMAGE, new AttributeModifier(BASE_ATTACK_DAMAGE_UUID, "Weapon modifier", damage, AttributeModifier.Operation.ADDITION));
        builder.put(Attributes.ATTACK_SPEED, new AttributeModifier(BASE_ATTACK_SPEED_UUID, "Weapon modifier", attackSpd, AttributeModifier.Operation.ADDITION));
        //Checking if the Forge 'Reach' Attribute is present
        if (ForgeMod.REACH_DISTANCE.isPresent()) {
            builder.put(ForgeMod.REACH_DISTANCE.get(), new AttributeModifier(REACH_MOD, "Weapon modifier", reach, AttributeModifier.Operation.ADDITION));
        }
        builder.put(Attributes.ATTACK_KNOCKBACK, new AttributeModifier(KNOCKBACK_MOD, "Weapon modifier", knockBack, AttributeModifier.Operation.ADDITION));
        map = builder.build();
        return map;
    });
  
    //Now you can modify the reach value and other attribute values per entry
    public ExampleReachItem(IItemTier tier, int dmg, float atkspd, double reach, double kb, Properties properties) {
        super(tier, dmg, atkspd, properties);
        this.damage = (int) ((float)dmg + tier.getAttackDamageBonus());
        this.attackSpd = (int) atkspd;
        this.reach = reach;
        this.knockBack = kb;
    }

    @Override
    public Multimap<Attribute, AttributeModifier> getAttributeModifiers(EquipmentSlotType slot, ItemStack stack) {
        return slot == EquipmentSlotType.MAINHAND ? ATTRIBUTE_LAZY_MAP.get() : super.getAttributeModifiers(slot, stack);
    }

    //This also works on blocks btw
    @Override
    public boolean onEntitySwing(ItemStack stack, LivingEntity entity) {
        double reach = entity.getAttributeValue(ForgeMod.REACH_DISTANCE.get());
        double reachSqr = reach * reach;
        World world = entity.level;

        Vector3d viewVec = entity.getViewVector(1.0F);
        Vector3d eyeVec = entity.getEyePosition(1.0F);
        Vector3d targetVec = eyeVec.add(viewVec.x * reach, viewVec.y * reach, viewVec.z * reach);

        //Expanding the attacker's bounding box by the view vector's scale, and inflating it by 4.0D (x, y, z)
        AxisAlignedBB viewBB = entity.getBoundingBox().expandTowards(viewVec.scale(reach)).inflate(4.0D, 4.0D, 4.0D);
        EntityRayTraceResult result = ProjectileHelper.getEntityHitResult(world, entity, eyeVec, targetVec, viewBB, EntityPredicates.NO_CREATIVE_OR_SPECTATOR);

        if (result == null || !(result.getEntity() instanceof LivingEntity)) return false;

        LivingEntity target = (LivingEntity) result.getEntity();

        double distanceToTargetSqr = entity.distanceToSqr(target);

        boolean hitResult = (result != null ? target : null) != null;

        if (hitResult) {
            if (entity instanceof PlayerEntity) {
                if (reachSqr >= distanceToTargetSqr) {
                    target.hurt(DamageSource.playerAttack((PlayerEntity) entity), attackDamage);
                  //Do stuff
                }
            }
        }
        return super.onEntitySwing(stack, entity);
    }
}

 

I'm bad at explaining stuff, so I apologize if I'm at any point unclear.

 

I hope this helps anybody having the same issue, or a similar issue of some sort.

 

Edit: The variables above the constructor don't have to be static, but they can be static. Me making them static was just force of habit XD. It was also a fault on my end for calling them in a non-static context inside my constructor.

Edited by Ninjaguy169
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

    • Hey, Me and my friends decided to start up a Server with "a few" mods, the last few days everything went well we used all the items we wanted. Now our Game crashes the moment we touch a Lava Bucket inside our Inventory. It just instantly closes and gives me an "Alc Cleanup"  Crash screen (Using GDLauncher). I honestly dont have a clue how to resolve this error. If anyone could help id really appreciate it, I speak German and Englisch so you can choose whatever you speak more fluently. Thanks in Advance. Plus I dont know how to link my Crash Report help for that would be nice too whoops
    • I hosted a minecraft server and I modded it, and there is always an error on the console which closes the server. If someone knows how to repair it, it would be amazing. Thank you. I paste the crash report down here: ---- Minecraft Crash Report ---- WARNING: coremods are present:   llibrary (llibrary-core-1.0.11-1.12.2.jar)   WolfArmorCore (WolfArmorAndStorage-1.12.2-3.8.0-universal-signed.jar)   AstralCore (astralsorcery-1.12.2-1.10.27.jar)   CreativePatchingLoader (CreativeCore_v1.10.71_mc1.12.2.jar)   SecurityCraftLoadingPlugin ([1.12.2] SecurityCraft v1.9.8.jar)   ForgelinPlugin (Forgelin-1.8.4.jar)   midnight (themidnight-0.3.5.jar)   FutureMC (Future-MC-0.2.19.jar)   SpartanWeaponry-MixinLoader (SpartanWeaponry-1.12.2-1.5.3.jar)   Backpacked (backpacked-1.4.3-1.12.2.jar)   LoadingPlugin (Reskillable-1.12.2-1.13.0.jar)   LoadingPlugin (Bloodmoon-MC1.12.2-1.5.3.jar) Contact their authors BEFORE contacting forge // There are four lights! Time: 3/28/24 12:17 PM Description: Exception in server tick loop net.minecraftforge.fml.common.LoaderException: java.lang.NoClassDefFoundError: net/minecraft/client/multiplayer/WorldClient     at net.minecraftforge.fml.common.AutomaticEventSubscriber.inject(AutomaticEventSubscriber.java:89)     at net.minecraftforge.fml.common.FMLModContainer.constructMod(FMLModContainer.java:612)     at sun.reflect.GeneratedMethodAccessor10.invoke(Unknown Source)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     at java.lang.reflect.Method.invoke(Method.java:498)     at com.google.common.eventbus.Subscriber.invokeSubscriberMethod(Subscriber.java:91)     at com.google.common.eventbus.Subscriber$SynchronizedSubscriber.invokeSubscriberMethod(Subscriber.java:150)     at com.google.common.eventbus.Subscriber$1.run(Subscriber.java:76)     at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:399)     at com.google.common.eventbus.Subscriber.dispatchEvent(Subscriber.java:71)     at com.google.common.eventbus.Dispatcher$PerThreadQueuedDispatcher.dispatch(Dispatcher.java:116)     at com.google.common.eventbus.EventBus.post(EventBus.java:217)     at net.minecraftforge.fml.common.LoadController.sendEventToModContainer(LoadController.java:219)     at net.minecraftforge.fml.common.LoadController.propogateStateMessage(LoadController.java:197)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     at java.lang.reflect.Method.invoke(Method.java:498)     at com.google.common.eventbus.Subscriber.invokeSubscriberMethod(Subscriber.java:91)     at com.google.common.eventbus.Subscriber$SynchronizedSubscriber.invokeSubscriberMethod(Subscriber.java:150)     at com.google.common.eventbus.Subscriber$1.run(Subscriber.java:76)     at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:399)     at com.google.common.eventbus.Subscriber.dispatchEvent(Subscriber.java:71)     at com.google.common.eventbus.Dispatcher$PerThreadQueuedDispatcher.dispatch(Dispatcher.java:116)     at com.google.common.eventbus.EventBus.post(EventBus.java:217)     at net.minecraftforge.fml.common.LoadController.distributeStateMessage(LoadController.java:136)     at net.minecraftforge.fml.common.Loader.loadMods(Loader.java:595)     at net.minecraftforge.fml.server.FMLServerHandler.beginServerLoading(FMLServerHandler.java:98)     at net.minecraftforge.fml.common.FMLCommonHandler.onServerStart(FMLCommonHandler.java:333)     at net.minecraft.server.dedicated.DedicatedServer.func_71197_b(DedicatedServer.java:125)     at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:486)     at java.lang.Thread.run(Thread.java:750) Caused by: java.lang.NoClassDefFoundError: net/minecraft/client/multiplayer/WorldClient     at java.lang.Class.getDeclaredMethods0(Native Method)     at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)     at java.lang.Class.privateGetPublicMethods(Class.java:2902)     at java.lang.Class.getMethods(Class.java:1615)     at net.minecraftforge.fml.common.eventhandler.EventBus.register(EventBus.java:82)     at net.minecraftforge.fml.common.AutomaticEventSubscriber.inject(AutomaticEventSubscriber.java:82)     ... 31 more Caused by: java.lang.ClassNotFoundException: net.minecraft.client.multiplayer.WorldClient     at net.minecraft.launchwrapper.LaunchClassLoader.findClass(LaunchClassLoader.java:191)     at java.lang.ClassLoader.loadClass(ClassLoader.java:418)     at java.lang.ClassLoader.loadClass(ClassLoader.java:351)     ... 37 more Caused by: net.minecraftforge.fml.common.asm.ASMTransformerWrapper$TransformerException: Exception in class transformer net.minecraftforge.fml.common.asm.transformers.SideTransformer@4e558728 from coremod FMLCorePlugin     at net.minecraftforge.fml.common.asm.ASMTransformerWrapper$TransformerWrapper.transform(ASMTransformerWrapper.java:260)     at net.minecraft.launchwrapper.LaunchClassLoader.runTransformers(LaunchClassLoader.java:279)     at net.minecraft.launchwrapper.LaunchClassLoader.findClass(LaunchClassLoader.java:176)     ... 39 more Caused by: java.lang.RuntimeException: Attempted to load class bsb for invalid side SERVER     at net.minecraftforge.fml.common.asm.transformers.SideTransformer.transform(SideTransformer.java:62)     at net.minecraftforge.fml.common.asm.ASMTransformerWrapper$TransformerWrapper.transform(ASMTransformerWrapper.java:256)     ... 41 more A detailed walkthrough of the error, its code path and all known details is as follows: --------------------------------------------------------------------------------------- -- System Details -- Details:     Minecraft Version: 1.12.2     Operating System: Linux (amd64) version 5.10.0-28-cloud-amd64     Java Version: 1.8.0_382, Temurin     Java VM Version: OpenJDK 64-Bit Server VM (mixed mode), Temurin     Memory: 948745536 bytes (904 MB) / 1564999680 bytes (1492 MB) up to 7635730432 bytes (7282 MB)     JVM Flags: 2 total; -Xmx8192M -Xms256M     IntCache: cache: 0, tcache: 0, allocated: 0, tallocated: 0     FML: MCP 9.42 Powered by Forge 14.23.5.2860 63 mods loaded, 63 mods active     States: 'U' = Unloaded 'L' = Loaded 'C' = Constructed 'H' = Pre-initialized 'I' = Initialized 'J' = Post-initialized 'A' = Available 'D' = Disabled 'E' = Errored     | State | ID                 | Version                 | Source                                                | Signature                                |     |:----- |:------------------ |:----------------------- |:----------------------------------------------------- |:---------------------------------------- |     | LC    | minecraft          | 1.12.2                  | minecraft.jar                                         | None                                     |     | LC    | mcp                | 9.42                    | minecraft.jar                                         | None                                     |     | LC    | FML                | 8.0.99.99               | forge-1.12.2-14.23.5.2860.jar                         | e3c3d50c7c986df74c645c0ac54639741c90a557 |     | LC    | forge              | 14.23.5.2860            | forge-1.12.2-14.23.5.2860.jar                         | e3c3d50c7c986df74c645c0ac54639741c90a557 |     | LC    | creativecoredummy  | 1.0.0                   | minecraft.jar                                         | None                                     |     | LC    | backpacked         | 1.4.2                   | backpacked-1.4.3-1.12.2.jar                           | None                                     |     | LC    | itemblacklist      | 1.4.3                   | ItemBlacklist-1.4.3.jar                               | None                                     |     | LC    | securitycraft      | v1.9.8                  | [1.12.2] SecurityCraft v1.9.8.jar                     | None                                     |     | LC    | aiimprovements     | 0.0.1.3                 | AIImprovements-1.12-0.0.1b3.jar                       | None                                     |     | LC    | jei                | 4.16.1.301              | jei_1.12.2-4.16.1.301.jar                             | None                                     |     | LC    | appleskin          | 1.0.14                  | AppleSkin-mc1.12-1.0.14.jar                           | None                                     |     | LC    | baubles            | 1.5.2                   | Baubles-1.12-1.5.2.jar                                | None                                     |     | LC    | astralsorcery      | 1.10.27                 | astralsorcery-1.12.2-1.10.27.jar                      | a0f0b759d895c15ceb3e3bcb5f3c2db7c582edf0 |     | LC    | attributefix       | 1.0.12                  | AttributeFix-Forge-1.12.2-1.0.12.jar                  | None                                     |     | LC    | atum               | 2.0.20                  | Atum-1.12.2-2.0.20.jar                                | None                                     |     | LC    | bloodmoon          | 1.5.3                   | Bloodmoon-MC1.12.2-1.5.3.jar                          | d72e0dd57935b3e9476212aea0c0df352dd76291 |     | LC    | forgelin           | 1.8.4                   | Forgelin-1.8.4.jar                                    | None                                     |     | LC    | bountiful          | 2.2.2                   | Bountiful-2.2.2.jar                                   | None                                     |     | LC    | camera             | 1.0.10                  | camera-1.0.10.jar                                     | None                                     |     | LC    | chisel             | MC1.12.2-1.0.2.45       | Chisel-MC1.12.2-1.0.2.45.jar                          | None                                     |     | LC    | collective         | 3.0                     | collective-1.12.2-3.0.jar                             | None                                     |     | LC    | reskillable        | 1.12.2-1.13.0           | Reskillable-1.12.2-1.13.0.jar                         | None                                     |     | LC    | compatskills       | 1.12.2-1.17.0           | CompatSkills-1.12.2-1.17.0.jar                        | None                                     |     | LC    | creativecore       | 1.10.0                  | CreativeCore_v1.10.71_mc1.12.2.jar                    | None                                     |     | LC    | customnpcs         | 1.12                    | CustomNPCs_1.12.2-(05Jul20).jar                       | None                                     |     | LC    | darknesslib        | 1.1.2                   | DarknessLib-1.12.2-1.1.2.jar                          | 220f10d3a93b3ff5fbaa7434cc629d863d6751b9 |     | LC    | dungeonsmod        | @VERSION@               | DungeonsMod-1.12.2-1.0.8.jar                          | None                                     |     | LC    | enhancedvisuals    | 1.3.0                   | EnhancedVisuals_v1.4.4_mc1.12.2.jar                   | None                                     |     | LC    | extrautils2        | 1.0                     | extrautils2-1.12-1.9.9.jar                            | None                                     |     | LC    | futuremc           | 0.2.6                   | Future-MC-0.2.19.jar                                  | None                                     |     | LC    | geckolib3          | 3.0.30                  | geckolib-forge-1.12.2-3.0.31.jar                      | None                                     |     | LC    | gottschcore        | 1.15.1                  | GottschCore-mc1.12.2-f14.23.5.2859-v1.15.1.jar        | None                                     |     | LC    | hardcorerevival    | 1.2.0                   | HardcoreRevival_1.12.2-1.2.0.jar                      | None                                     |     | LC    | waila              | 1.8.26                  | Hwyla-1.8.26-B41_1.12.2.jar                           | None                                     |     | LE    | imsm               | 1.12                    | Instant Massive Structures Mod 1.12.2.jar             | None                                     |     | L     | journeymap         | 1.12.2-5.7.1p2          | journeymap-1.12.2-5.7.1p2.jar                         | None                                     |     | L     | mobsunscreen       | @version@               | mobsunscreen-1.12.2-3.1.5.jar                         | None                                     |     | L     | morpheus           | 1.12.2-3.5.106          | Morpheus-1.12.2-3.5.106.jar                           | None                                     |     | L     | llibrary           | 1.7.20                  | llibrary-1.7.20-1.12.2.jar                            | None                                     |     | L     | mowziesmobs        | 1.5.8                   | mowziesmobs-1.5.8.jar                                 | None                                     |     | L     | nocubessrparmory   | 3.0.0                   | NoCubes_SRP_Combat_Addon_3.0.0.jar                    | None                                     |     | L     | nocubessrpnests    | 3.0.0                   | NoCubes_SRP_Nests_Addon_3.0.0.jar                     | None                                     |     | L     | nocubessrpsurvival | 3.0.0                   | NoCubes_SRP_Survival_Addon_3.0.0.jar                  | None                                     |     | L     | nocubesrptweaks    | V4.1                    | nocubesrptweaks-V4.1.jar                              | None                                     |     | L     | patchouli          | 1.0-23.6                | Patchouli-1.0-23.6.jar                                | None                                     |     | L     | artifacts          | 1.1.2                   | RLArtifacts-1.1.2.jar                                 | None                                     |     | L     | rsgauges           | 1.2.8                   | rsgauges-1.12.2-1.2.8.jar                             | None                                     |     | L     | rustic             | 1.1.7                   | rustic-1.1.7.jar                                      | None                                     |     | L     | silentlib          | 3.0.13                  | SilentLib-1.12.2-3.0.14+168.jar                       | None                                     |     | L     | scalinghealth      | 1.3.37                  | ScalingHealth-1.12.2-1.3.42+147.jar                   | None                                     |     | L     | lteleporters       | 1.12.2-3.0.2            | simpleteleporters-1.12.2-3.0.2.jar                    | None                                     |     | L     | spartanshields     | 1.5.5                   | SpartanShields-1.12.2-1.5.5.jar                       | None                                     |     | L     | spartanweaponry    | 1.5.3                   | SpartanWeaponry-1.12.2-1.5.3.jar                      | None                                     |     | L     | srparasites        | 1.9.18                  | SRParasites-1.12.2v1.9.18.jar                         | None                                     |     | L     | treasure2          | 2.2.0                   | Treasure2-mc1.12.2-f14.23.5.2859-v2.2.1.jar           | None                                     |     | L     | treeharvester      | 4.0                     | treeharvester_1.12.2-4.0.jar                          | None                                     |     | L     | twilightforest     | 3.11.1021               | twilightforest-1.12.2-3.11.1021-universal.jar         | None                                     |     | L     | variedcommodities  | 1.12.2                  | VariedCommodities_1.12.2-(31Mar23).jar                | None                                     |     | L     | voicechat          | 1.12.2-2.4.32           | voicechat-forge-1.12.2-2.4.32.jar                     | None                                     |     | L     | wolfarmor          | 3.8.0                   | WolfArmorAndStorage-1.12.2-3.8.0-universal-signed.jar | None                                     |     | L     | worldborder        | 2.3                     | worldborder_1.12.2-2.3.jar                            | None                                     |     | L     | midnight           | 0.3.5                   | themidnight-0.3.5.jar                                 | None                                     |     | L     | structurize        | 1.12.2-0.10.277-RELEASE | structurize-1.12.2-0.10.277-RELEASE.jar               | None                                     |     Loaded coremods (and transformers):  llibrary (llibrary-core-1.0.11-1.12.2.jar)   net.ilexiconn.llibrary.server.core.plugin.LLibraryTransformer   net.ilexiconn.llibrary.server.core.patcher.LLibraryRuntimePatcher WolfArmorCore (WolfArmorAndStorage-1.12.2-3.8.0-universal-signed.jar)    AstralCore (astralsorcery-1.12.2-1.10.27.jar)    CreativePatchingLoader (CreativeCore_v1.10.71_mc1.12.2.jar)    SecurityCraftLoadingPlugin ([1.12.2] SecurityCraft v1.9.8.jar)    ForgelinPlugin (Forgelin-1.8.4.jar)    midnight (themidnight-0.3.5.jar)   com.mushroom.midnight.core.transformer.MidnightClassTransformer FutureMC (Future-MC-0.2.19.jar)   thedarkcolour.futuremc.asm.CoreTransformer SpartanWeaponry-MixinLoader (SpartanWeaponry-1.12.2-1.5.3.jar)    Backpacked (backpacked-1.4.3-1.12.2.jar)   com.mrcrayfish.backpacked.asm.BackpackedTransformer LoadingPlugin (Reskillable-1.12.2-1.13.0.jar)   codersafterdark.reskillable.base.asm.ClassTransformer LoadingPlugin (Bloodmoon-MC1.12.2-1.5.3.jar)   lumien.bloodmoon.asm.ClassTransformer     Profiler Position: N/A (disabled)     Is Modded: Definitely; Server brand changed to 'fml,forge'     Type: Dedicated Server (map_server.txt)
    • When i add mods like falling leaves, visuality and kappas shaders, even if i restart Minecraft they dont show up in the mods menu and they dont work
    • Delete the forge-client.toml file in your config folder  
    • If you are using AMD/ATI, get the latest drivers from their website - do not update via system  
  • Topics

×
×
  • Create New...

Important Information

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