How do I detect a collision between a KinematicBody2D and a StaticBody2D.

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

I’m learning Godot after switching over from Unity, and one thing that I can’t figure out how to accomplish is collision detection. In unity, there was a function that would be called upon each collision, that would allow you to manipulate the colliding object.

Basically, I have a KinematicBody2D player, and I want to be able to call a ‘die’ function when it touches a StaticBody2D I have. There are multiple StaticBody2Ds that I want to detect. In Unity, I was able to place tags on all of the bodies, then check that tag on collision, but I can’t figure out how to detect collisions at all, let alone any information about the collided body.

Here’s the script I have attached to my player:

func body_enter(body):
	if (body.get_name() == "Lava"):

Here’s my hierarchy, if its offers any help:

:bust_in_silhouette: Reply From: denxi

A couple of things:

  1. I’m assuming that your player scene has a collision body, and that all the collision layers and masks are set up correctly.

  2. When using KinematicBodies, the move_and_slide and move_and_collide functions return information about the collision(s) that occurred during the motion. I dunno if you’re using these properly, the code you’ve provided only shows the custom function you have for a response to the collision.

  3. Using body.get_name() has a lot of limitation for what you’re looking for. In this case, only the one “Lava” is actually named that, so it’ll be the only one picked up. Instead, you could either add your Lava blocks to a group called “Lava” in their _ready func, and then check to see if body.is_in_group("Lava"). You could also instead have a specific collision layer that is reserved for collisions that will kill the player, and then check if body.get_collision_layer_bit(X) is a true, where X is the collision layer that you’ve put Lava on.

How would I use the move_and_collide function? I tried using it like I would in Unity, by calling it along side the “func _physics_process(delta):” line. However, that throws an error. Should this be inside the “func _physics_process(delta):” function, with move_and_slide()? If so, how would I format that?

cvieira | 2020-05-01 14:04

You don’t use both movement methods, you use one or the other. Use move_and_slide() if you want slide response when colliding.

I highly recommend reading this, it explains and shows examples:
Using KinematicBody2D — Godot Engine (3.2) documentation in English

kidscancode | 2020-05-01 16:02