Area collision not working?

Godot Version

Using Godot Web Editor 4.6.2

Question

Hello. I’m currently making a game with tile-based movement. Right now, I’m trying to make collectables. All you have to do, is step on the same space as the collectable to pick it up.

I’m using Area2D signals for pickups, but for some reason nothing is being detected, despite being on the same collision layer. The code for both the player and the collectable is down below. Please help me fix.

Player:

extends CharacterBody2D

const grid = 16

@onready var down: RayCast2D = $down
@onready var up: RayCast2D = $up
@onready var left: RayCast2D = $left
@onready var right: RayCast2D = $right

func _process(delta: float) -> void:
	pass
	
	# Grid-based movement lol
	if Input.is_action_just_pressed("up") and not up.is_colliding():
		position += Vector2(0, -grid)
	
	if Input.is_action_just_pressed("down") and not down.is_colliding():
		position += Vector2(0, grid)
	
	if Input.is_action_just_pressed("left") and not left.is_colliding():
		position += Vector2(-grid, 0)
	
	if Input.is_action_just_pressed("right") and not right.is_colliding():
		position += Vector2(grid, 0)

Collectable:

extends StaticBody2D

@onready var player: CharacterBody2D = $"../Player"

func _on_coin_body_entered(body):
	queue_free()

I’m not sure if StaticBody2D can receive body entered signals, unless I’m missing something, since I don’t see your Area2D anywhere.

2 Likes

Change your code, and make sure the coin is an Area2D and not a StaticBody2D. I added in some code for passing the collected coin to the player because I could see you were planning on that and going down the wrong path.

extends CharacterBody2D

const grid = 16

var coins: int = 0

@onready var down: RayCast2D = $down
@onready var up: RayCast2D = $up
@onready var left: RayCast2D = $left
@onready var right: RayCast2D = $right


func _process(delta: float) -> void:
	pass
	
	# Grid-based movement lol
	if Input.is_action_just_pressed("up") and not up.is_colliding():
		position += Vector2(0, -grid)
	
	if Input.is_action_just_pressed("down") and not down.is_colliding():
		position += Vector2(0, grid)
	
	if Input.is_action_just_pressed("left") and not left.is_colliding():
		position += Vector2(-grid, 0)
	
	if Input.is_action_just_pressed("right") and not right.is_colliding():
		position += Vector2(grid, 0)


func collect(item: Node) -> void:
	if item is Coin:
		coins += 1
		print("Coins collected: %s" % [coins])
class_name Coin extends Area2D


func _on_coin_body_entered(body: Node2D):
	body.collect(self)
	queue_free()