Need help checking collisions for a characterbody2d

Godot Version



I need help with an object that can collide with the tile map but is deleted when the player touches it. It is a characterbody2d as of right now. The code below is what I have now.

extends CharacterBody2D

var speed = 5
var random1 = randf_range(-1,1)
var random2 = randf_range(-1,1)
@onready var animated_sprite_2d = $AnimatedSprite2D

func _ready():

func _process(delta):
animated_sprite_2d.speed_scale = randf_range(.5,1.2)
var screen_size = get_viewport_rect().size
position = position.clamp(Vector2.ZERO, screen_size)
position.x += random1 * speed
position.y += random2 * speed
random1 += randf_range(-.1,.1)
random2 += randf_range(-.1,.1)
if random1 < -1 :
random1 = -1
if random1 > 1 :
random1 = 1
if random2 < -1 :
random2 = -1
if random2 > 1 :
random2 = 1

if random1 > .2:
	animated_sprite_2d.flip_h = false
if random1 < -.2:
	animated_sprite_2d.flip_h = true


func _on_area_2d_body_entered(body):
if ( == “player”):

to check collision from characterbody2d and if it collides with player, then queue free itself:

for i in get_slide_collision_count():
	var collision = get_slide_collision(i)
	if collision.get_collider():
		if collision.get_collider().name=="player":

put the codes in func _physics_process(delta):

So adding a area2d to it and checking _on_area_2d_body_entered wouldn’t work?

well it works, but you will need an extra area2d to check if the player enters it or not, this will be useful if you want to have a ranged area larger than the enemy body collision shape

well that is exactly what i have and it is not working.

because the area2d is the same size like the body collision shape? hence the player never enters it

no matter how big the area2d is it doesn’t detect it. I am using this though so maybe thats where the problem is:

func _on_area_2d_body_entered(body):
if ( == “player”):

well um, if the collision code works, then no need for this anymore
it also could be just your naming is not 100% precise, you sure the body that entered the area is named “player”?

it is when i remove the if body name part it works though. it just instantly deletes itself.

some other things could be entered it, that’s not player. try print(

That helped. I managed to fix it thanks so much!

1 Like