How do you do knockback

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Dava
:warning: Old Version Published before Godot 3 was released.

I have been trying to implement knockback with all attempts with fail, how do you do implement knockback depending on the damage taken and make the object bounce off the wall depending on the knockback strength

:bust_in_silhouette: Reply From: Zylann

I assume the damage taken comes from some sort of projectile or weapon. If so, you have to take the motion vector of that object, and apply it on your character as an impulse.

If your character and projectiles are rigidbodies, it would look like that in code:

	# Tweak to what you want
const KNOCKBACK_FORCE = 1.0

func hit_by_object(projectile_rigidbody):
	var direction = projectile_rigidbory.get_linear_velocity().normalized()
    # Apply impulse to the center of the object
	self.apply_impulse(Vector2(0,0), direction * KNOCKBACK_FORCE)

If the source of the knockback isn’t moving (i.e. its linear velocity is zero), you can get the direction this way instead:

	var direction = (self.get_global_pos() - projectile_rigidbody.get_global_pos()).normalized()

If you have access to hit informations, you can do this:

self.apply_impulse(hit.positipn, -hit.normal * KNOCKBACK_FORCE)

doesn’t apply_impulse() take two arguments?

timoschwarzer | 2016-07-04 22:05

Yeah, you also have to specify the local position at which the impulse must be applied on the object. In case of an impact, you can give hit.position, or the center of the object if you don’t have a specific position. For the direction, use -hit.normal.

Zylann | 2016-07-04 22:36

Thank you for the helpful answer

Dava | 2016-07-05 10:29