Need help checking collisions for a characterbody2d

Godot Version

4.2.1

Question

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():
pass

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


move_and_slide()

func _on_area_2d_body_entered(body):
if (body.name == “player”):
queue_free()

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":
			queue_free()

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 (body.name == “player”):
queue_free()

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(body.name)

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

1 Like