How to detect when a ChatacterBody3d collides with another CharacterBody3d?

Godot Version

4.2.1

How to detect when a ChatacterBody3d collides with another CharacterBody3d?
I’m trying to make it so that when enemies (which are CharacterBody3d) collide with the player (another CharacterBody3d) then it starts a “hit” function and removes health from the player.

My player is in the “player collision layer” (layer 3) and the enemies are in their “enemy collision layer” (layer 4).
I want to start the “hit” function only when objects in the “enemy collision layer” collide with the player, how do I make it?

I could make this work with areas3d, but then I would need to duplicate the collision shapes of the enemies or the player, and this seems like a huge waste of resources when there are collisionshapes already working. There must be a better way right? How I do make this?

In the docs I found get_slide_collision(), but I don’t know how to use it, nor how to make it filter certain layers (only detect enemy layer).

I also need to detect which enemy collided with the player, so that each enemy deals different amounts of damage, is there a way to do this as well?

The move_and_collide function will move and stop movement when colliding. You can decide how to handle the collision based on the KinematicCollision3D that it returns.

Edit: I’d written “2D” instead of “3D”; here’s the function: PhysicsBody3D — Godot Engine (stable) documentation in English

1 Like

Thanks, I didn’t know I could use move_and_collide like that, I solved it by doing this:

if move_and_collide(Vector3.ZERO, true):
		if move_and_collide(Vector3.ZERO, true).get_collider().get_collision_layer() == 8:
			PlayerStats.health -= (move_and_collide(Vector3.ZERO, true).get_collider().enemy_stats.stats.attack)