How to check for collisions

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

I feel like this should be really simple but I’m struggling to find out how to do it;

I have a player (KinematicBody2D with a collision shape 2D) and an enemy (with the exact same child nodes), and in the player script I want to check whether the two collide so I can damage the player. What is the easiest way to do this?

:bust_in_silhouette: Reply From: mrLogan

I think the piece of the puzzle you might be reaching for is that move_and_collide actually returns a KinematicCollision2D object which contains the object it collided with

for example:

  var kb2d = self.move_and_collide(velocity*delta)
  if (kb2d):
    	print("collided with" + str(kb2d.collider_id))

for more detail check out the page at KinematicCollision2D — Godot Engine (3.0) documentation in English

There is also a section in “Tutorials” all about using kinematic bodies:
Using CharacterBody2D/3D — Godot Engine (latest) documentation in English

kidscancode | 2018-05-04 13:45

For whatever reason changing my move_and_slide to move_and_collide is really not working for me. Is there any way to check collisions while still using move_and_slide?

hotmailking | 2018-05-05 03:58

You can use either. move_and_collide() returns a KinematicCollision2D. If you’re using move_and_slide() you need to use get_slide_count() and get_slide_collision(), which also returns a KinematicCollision2D.

kidscancode | 2018-05-05 04:05

Okay I’m using that but it’s only returning my player colliding with the ground and not when it collides with the enemy.

hotmailking | 2018-05-05 04:26

Nevermind, working now. But how do I check what object it is the KinematicCollision2D is related to? At the moment it’s just returning a number.

hotmailking | 2018-05-05 04:30

Nevermind again hahaha. Got it all working. Cheers for the help

hotmailking | 2018-05-05 04:38