I’m working on a code where if the bullet touches the enemy, it disappears. But when I run the game, it disappears before I even shoot the bullet, I don’t know what’s making this happen
CODE:
extends CharacterBody2D
var bullet = "res://scenes/attacks/bullet.tscn"
func _on_hitbox_body_entered(_body):
if bullet:
queue_free()
else:
pass
Your code is falling because your check inside _on_hitbox_body_entered is wrong. This if bullet will always be true so basically any body that enters this area will trigger the enemy destruction, bullet in your code is a string and any non-empty string evalutes to true.
If you want to check correctly you need to use the body parameter for this:
#In your bullet script:
# Add the node to the "bullet group"
func _ready() -> void:
add_to_group("bullet")
#In your enemy code:
extends CharacterBody2D
var bullet = "res://scenes/attacks/bullet.tscn"
func _on_hitbox_body_entered(body):
# Check if the body that collided is from the "bullet" group
if body.is_in_group(body):
queue_free()
else:
pass