How to promote knockBack ability of sword and arrow?

I want use sword let player knock back farther than vanilla

While there isnt an api that i know of to just set the knockback strength. You can manually set the knockback of the player.

Just listen for the damage event. Check the damage modifier for sword and then set the velocity of the players direction multiplied by -1 (the lower the number the more the knockback will be).

How to exactly know damage from sword?

Sorry thought it was a DamageModifier. Use the EventContext, im not sure how to check if the item is a forge item sword, however every case i know, they have the name “sword” in the ItemType name, so thats what I did in the example. Oh and the example has been tested using Sponge without any mods and works fine.

    Optional<ItemStackSnapshot> opItem = event.getContext().get(EventContextKeys.USED_ITEM);
    if(!opItem.isPresent()){
        return;
    }
    ItemStackSnapshot item = opItem.get();
    if(item.getType().getName().toLowerCase().contains("sword")){
        System.out.println("Damage used sword");
    }

I’m not sure the arrow will be any more special, but I will try to figure it out , thank you very very much!

Your welcome, tell me if anything is different, I know a way to get the projectile that hit the player and the player who fired it if the sword way doesn’t work.

EventContextKeys.USED_ITEM is work, but need some judgments before get item. see:

now, the problem is, can’t process knockback well, I try:

victim.setVelocity(victim.getVelocity().mul(-5));

or

victim.setVelocity(victim.getRotation().mul(-5));

It doesn’t look like it’s multiplied by -5, I think the player knockback(velocity) is probably set after EntityDamageEvent. So, if i use getVelocity it maybe return 0,0,0, or use getRotation, it’s more hard too process, because if you attack him, maybe he was back on you, then multiplied by -5, the knockback direction is not correct.

Because the velocity is 0,0,0. It maybe best to set the velocity away from the attacker. If the minecraft engine overrides the velocity, try a schedule of a single tick and then set the velocity after.

Here is the code for moving away from a location.

Location<World> loc;
Player player;

Vector3i vector =  loc.getBlockPos().subtract(player.getLocation().getBlockPos();
player.setVelocity(vector);

Im not near a pc so sorry if i get the Sponge API incorrect

Smart! i know you meaning, just use player1.loc subtract player2.loc, but If a player is too far away another player, i want to know how to control the strength. Does player1.loc.normaliz subtract player2.loc.normaliz work?

Try it :wink: sadly i dont have all the answers.

1 Like