Get collider name with KinematicBody

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

I want to get the name of the body the player collided with, if the player collided with a body. How can I do this?

:bust_in_silhouette: Reply From: kidscancode

Collision info is contained in a KinematicCollision object.

How you access this, depends on how you’re moving your KinematicBody.

  1. If using move_and_collide(), it’s the returned value of the function:
var collision = move_and_collide(velocity * delta)
if collision:
    print(collision.collider.name)
  1. If using move_and_slide(), you can get collision data with get_slide_collision(). However, you have to keep in mind that when using this method, it’s possible to have multiple collisions in a single frame (when you move into a corner, for example):
velocity = move_and_slide(velocity, Vector3.UP)
for index in get_slide_count():
    var collision = get_slide_collision(index)
    print(collision.collider.name)

Please see the KinematicBody reference for details.