KingRealzYT
KingRealzYT

Reputation: 41

How would i change it so it happens to all Entities and not just Players Minecraft Forge Modding

I want it so my swords will effect all entities, not just players (rn it is only players) How would i change my code so that if it hits an entity there is a chance that the effect will happen instead of having it 100% and only on players? Here is my code:

@SubscribeEvent
    public static void swordEffects(TickEvent.WorldTickEvent event) {
        if (Minecraft.getInstance().player != null) {
            if (Minecraft.getInstance().player.inventory.getCurrentItem().equals(ModItems.BLACK_IRON_SWORD)) {
                Minecraft.getInstance().player.addPotionEffect(new EffectInstance(Effects.SLOWNESS, 3600, 3));
            }

Upvotes: 1

Views: 987

Answers (1)

hohserg
hohserg

Reputation: 452

First, you need to understand the separation of game logic to the client and server sides.

Explore this: https://mcforge.readthedocs.io/en/1.15.x/concepts/sides/

In your code, you take a player from Minecraft.getInstance().player, it's a instance of the main player on client. This means that this code can only be run from the client side => server knows nothing about the effect application => effect won't really be applied.

To apply the effect to the entity which hold a sword in hand, use override of inventoryTick method in the class of your sword's item. Entity instance, which hold sword in their inventory, exists in arguments of inventoryTick. Check that the sword is in hand of entity and give the effect.

public class CustomSword extends SwordItem {

    @Override
    public void inventoryTick(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {
        if(isSelected && entityIn instanceof LivingEntity)
            ((LivingEntity) entityIn).addPotionEffect(new EffectInstance(Effects.SLOWNESS, 3600, 3));
    }

    ...
}

Name of inventoryTick method may be different depending on mappings. I used mappings channel: 'snapshot', version: '20201028-1.16.3'

Upvotes: 2

Related Questions