Get collision info between 2 CharacterBody2D

Godot Version
4.2.1

Question

Hey.
I have a player CharacterBody2D wich is moved with the keyboard and a CharacterBody2D Enemy that moves towards the player. I just want to apply damage to the player when he get “hit” by the enemy.
How can i detect a collision between the 2 CharacterBody2D?
I’ve tried on the Player script:

move_and_slide()

for i in get_slide_collision_count():
	var collision = get_slide_collision(i)
	print("Player Collided with: ", collision.get_collider().name)

But i only get the name. Is there a way to get either the group the collider is in, or the object so i can run an “hit” method.
Thanks

Here are 2 possible solutions, I think converting to the correct class is better, because then the editor lists the functions.

	for i in get_slide_collision_count():
		var collision = get_slide_collision(i)

		var collider = collision.get_collider()
		var enemy : Enemy = collider as Enemy

		if collider.is_in_group("Enemy"):
			print("is_in_group Enemy")
			collider.hit()

		if enemy:
			print("collider as Enemy")
			enemy.hit()

1 Like

Thanks, it works.
Do you have any idea on how to make the function “hit” only execute once or every x seconds?

A Timer Node also possible

Or save last timestamp, only hit if > 1000 ms

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.