I'm trying to make a clone of Super Crate Box (simple 2D platformer with shooting mechanics; just to learn Godot). I'm not sure how to implement the knockback effect when enemy gets hit by a bullet.

In order to check for collisions I use Area2D. The bullets checks for collision with the script like so:

``````# BULLET
func _on_Area2D_body_enter( body ):
if body.get_meta("type") == "enemy":
set_process(false)
body.get_hit(5, (get_global_pos() - body.get_global_pos()).normalized() * 100)
queue_free()
else:
pass
``````

On the enemy the `get_hit()` function looks as follows:

``````# ENEMY
func get_hit(dmg, force):
# print("Got hit with dmg: " + str(dmg) + "and force of: " + str(force))
health -= dmg
move(force)
``````

In this code the idea was to compute the difference in positions between the bullet and the enemy at the moment the bullet hits. I could then use this vector (or just it's horizontal part) to move the enemy back a bit. Unfortunately the computed vector is unreliable. Sometimes its horizontal (x) part is has opposite sign than expected.

To be honest I'm not sure I should be using Area2D and checking for its entering and leaving. The enemy and the bullet are KinematicBody2D. I don't need any elaborate physics in this game. Simple knockback seems like a job for a force impulse but that would require RigidBody2D... am I right?

How should I go about it? Should I stick to Area2D for collision checking?

Also I'm new so I hope I made this question as concise and as clear as possible and I did everything according to the rules. If not please let me know.

in Engine

You could use the vector of the bullet's flying direction to calculate the knockback angle and the bullet's speed for the force.

Heavy btw, you know, getting hit by bullet does NOT knock you back, thats 110% hollywood ;D

Using the bullets velocity vector makes a lot of sense actually... Thank you.

+1 vote
The normal direction should just be the `(B - A).normalized()`. Where B is your point of contact for the bullet, and A is your point of origin of the bullet.
I used the point of origin and the point of collision (only x part of difference of those two). I also used `move_to()` function. Seems to work good for now. Thank you.