How do i check for specific collisions in godot in only the code?

55 Views Asked by At

I am currently Trying out Godot, ANd nomatter what i search i cant seem to find out how to check collisions inside of the code in a working mannar.

This is my current code for moving my player.

extends CharacterBody2D

@export var SPEED = 10
func _ready():
    pass 


func _process(delta):
    #i want the player to collide with the item here in an if statement.
    if Input.is_key_pressed(KEY_W):
        move_local_y(-SPEED)
    if Input.is_key_pressed(KEY_S):
        move_local_y(SPEED)
    if Input.is_key_pressed(KEY_A):
        move_local_x(-SPEED)
    if Input.is_key_pressed(KEY_D):
        move_local_x(SPEED)

The item im trying to collide with is an Area2D with a Collisionshape2D as its child. Is there any way to help me with this?

1

There are 1 best solutions below

0
On

It's difficult to locate your problem without seeing the scenetree, but generally speaking the easiest way would be using a signal.

When you select your Area2D and click on the "Node" tab on the right site, next to "Inspector", you will find different signals that are built-in the Area2D class. You can then double-click "body_entered" and select the script you showed us above.

After that a new function should pop up under your _process() which will called everytime you character hits the Area2D.

Another way would be to check with get_slide_collision_count() if there are any collisions and then with get_slide_collision(slide_idx: int) who your player is colliding with.

Depending on what your quest is, one or the other might be more useful!