# Simulate a player knockback

Discussion in 'Spigot Plugin Development' started by TheGamerPlayz, May 31, 2016.

1. ### TheGamerPlayz

How would i simulate a player being knocked back? I was thinking of using set velocity, but that didn't seem a very efficient way as I couldn't always determine which direction the player would be hit in. Any suggestions?

2. ### JacobCrofts

Setting velocity sounds like the right way to go. You can determine the direction in which the player should be hit by drawing a vector between the attacker (or the arrow, in the event of a projectile hit) and the target.

This is what I'm using to determine a player's velocity, given the x and z components of the attack and the speed at which a player should be knocked back (0.5 is a typical speed, IIRC, but you can play around with it):

Code (Text):
private Vector getVelocity(double x, double z, double speed) {
double y = 0.3333; // this way, like normal knockback, it hits a player a little bit up
double multiplier = Math.sqrt((speed*speed) / (x*x + y*y + z*z)); // get a constant that, when multiplied by the vector, results in the speed we want
return new Vector(x, y, z).multiply(multiplier).setY(y);
}

3. ### TheGamerPlayz

I just determined got this =)
Code (Text):
target.setVelocity(attacker.getLocation().getDirection().multiply(2));
It takes the target and launches them into the direction the attacker is looking at making it great for this.

• Like x 1