emit_signal on collision between area2d and kinematicbody2d

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By rasmushassenkam

Hi, I am learning godot and I have some problems with collision detection.
I am doing a top down shooter, and I have a bullet which is an Area2d and an enemy which is a Kinematicbody2d, both have a CollisionShape2d attached. I have connected an on_body_entered to the bullet, in this I want to emit a signal and connect this to the enemy to let it know that it had been hit. My problem is that it seems like the enemy does not observe the signal. i’ve tried putting in a print in on_body_entered in the bullet, and that fires every time the enemy is hit, but I want to be able to detect this hit in the enemy. I’ve pasted in the code for the bullet and enemy below.

Bullet:

extends Area2D

var velocity = Vector2.ZERO

signal hit

func _physics_process(delta):
	position += velocity * delta


func _on_VisibilityNotifier2D_screen_exited():
	queue_free()	


func _on_Bullet_body_entered(body):
	emit_signal("hit")
	queue_free()

Enemy:

extends KinematicBody2D


func _on_Bullet_hit():
	print("I'm hit")

I edited your post for code formatting. In future, please try and format your code samples (4 spaces before each line, or there’s a button in the editor).

kidscancode | 2020-05-20 18:48

:bust_in_silhouette: Reply From: kidscancode

Did you connect the hit signal to the enemy? Either way, you really don’t need to do this.

The body_entered signal you are using already knows what entered - that’s why it passes a body parameter. body is a reference to the body that entered the area. So in your code you can do whatever you need to do with the enemy there

Example:

func _on_Bullet_body_entered(body):
    print("hit: ", body.name)  # this will show the name of the enemy node
    body.queue_free()  # this will remove the enemy you hit
    body.take_damage(2)  # if your enemy has a "take_damage" function, you can call it
    queue_free()

I thought I was overcomplicating stuff, but still new to the engine and learning. Thank you so much for the quick answer, it is much appreciated!

rasmushassenkam | 2020-05-20 19:15