Search code examples
collision-detectiongodot

How do I detect collision in Godot?


I'm making a game in Godot and I can't figure out what code I can use for a Death Plane (an area where an entity passes through and it de-spawns or dies).


Solution

  • To detect a collision in Godot you use Collision Objects, that is one of these:

    • Area (or Area2D)
    • StaticBody (or StaticBody2D)
    • RigidBody (or RigidBody2D)
    • KinematicBody (or KinematicBody2D)

    And you give it a CollisionShape (or CollisionShape2D) or CollisionPolygon (or CollisionPolygon2D) as a child. Of course, the CollisionShape (or CollisionShape2D) or CollisionPolygon (or CollisionPolygon2D) needs to have a configured shape.

    If you don't set your shapes correctly, not only the Collision Object will not work, but you will have a warning icon in the scene tree tell you to do set the shape.


    Usually the player avatar will be a KinematicBody (or KinematicBody2D), since those are intended to be moved by code.

    RigidBody (or RigidBody2D) is controlled by physics (it bounces, and so on), and StaticBody (or StaticBody2D) don't move.

    Thus none of those are what you want to use to detect when the player entered a particular zone. For that you use Area (or Area2D).


    As per where to put the code, the Area (or Area2D) will emit a signal body_entered when something enters and body_exited when something leaves. Connect the signal to a script where you write the code to handle that situation.


    By the way, you can simply attach an script to your KinematicBody (or KinematicBody2D) and in its _physics_process check for its vertical coordinate for a quick and simple Death Plane functionality.