#knockback

1 messages · Page 1 of 1 (latest)

sand linden
#
import { world } from '@minecraft/server';


const normalize = (x, z) => {
    const magnitude = Math.sqrt(x * x + z * z);
    return magnitude === 0 ? { x: 0, z: 0 } : { x: x / magnitude, z: z / magnitude };
};


world.afterEvents.entityHitEntity.subscribe((event) => {
    const attacker = event.damagingEntity; 
    const target = event.hitEntity; 

    if (!attacker || !target) return;

    
    if (attacker.typeId === 'minecraft:player') {
        const player = attacker;

        
        const { x, z } = normalize(player.getViewDirection().x, player.getViewDirection().z);

        if (player.isSprinting) {
            
            const sprintSpeed = Math.sqrt(player.velocity.x ** 2 + player.velocity.z ** 2);

            
            const horizontalKnockback = -0.2 * sprintSpeed; 
            const verticalKnockback = -0.1 * sprintSpeed; 
            target.applyKnockback(x * horizontalKnockback, z * horizontalKnockback, verticalKnockback, 0);
        } else {
            
            target.applyKnockback(0, 0, 0, 0); // Pas de knockback
        }
    }
});

console.log('Sprint Knockback v3');```
#

hi i have this error with this script
:
[Scripting][error]-TypeError: cannot read property 'x' of undefined at <anonymous> (sprintkb.js:25)

hollow jasper
#

What version of the API are you using?

sand linden
#

i think the error is here

const sprintSpeed = Math.sqrt(player.velocity.x ** 2 + player.velocity.z ** 2);```
hollow jasper
#

Because this looks like code for 1.19 or lower

sand linden
#

I think I'm using the most recent one

sand linden
hollow jasper
#

In that case, a few things:

  • player.velocity should be getVelocity()
  • applyKnocback takes an object: player.applyKnockback({x: 0, z: 0}, 5)
    • Horizontal force and vertical force baked in
#

This is assuming you are using the newest one SCyes

sand linden
#

like the player.velocity should be player.getVelocity ?

hollow jasper
#

player.getVelocity().x for example

#

similar to getViewDirection

#

That said, I am unsure why it didn't give you an error for that

#

I think it used to be .velocity