Reputation: 1
Hello and thanks for your time :) I have tried to make a simple sword that attacks and hits a mushroom, on hit the mushroom should play an animation. For some reason it wont ever interact with my sword, as if its on a different layer.
The scene hierachy, is a player scene, where i have added Node2D (named weapon), with an animatedSprite2d and an area2d (named hitbox). enter image description here
The weapon has a script that looks like this
extends Node2D
@onready var animated_sprite = $AnimatedSprite2D
@onready var collision_shape = $Hitbox/CollisionShape2D
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta):
if Input.is_action_just_pressed("attack"):
collision_shape.disabled = false
print(collision_shape.disabled)
animated_sprite.play("sword_attack")
else:
collision_shape.disabled = true
print(collision_shape.disabled)
func _on_hitbox_body_entered(body):
print("on body entered")
if body.is_in_group("hit"):
body.on_hit()
The mushroom script looks like this
extends Node2D
@onready var animated_sprite = $AnimatedSprite2D
func on_hit():
animated_sprite.play("slash_mushroom")
#queue_free() when animation is over.
Both the sword and the mushroom has their layer and mask set to 3. The mushroom holds the group variable "hit" attached to its Node2D.
The swords print line, under "_on_hitbox_body_entered" never prints, so i know this is where the problem is, but i can't tell why it wont interact, any help is mostly appreciated :)
I tried... Looking into the target (mushroom) Node --> Group, which is attached to its node2d and named "hit" with lower case.
Checking the layer and mask, but its all set to 3
Checking if the on_body_entered is correctly attached from the area2d(ergo hitbox), on double click it takes me to the swords hitbox func as shown above.
Made sure the swords collision was enabled, by showing prints in the if statement above, which seems to work.
EDIT---------------------- I have made some progress, apparently on_body_entered wont trigger on the mushroom, but on_area_entered will trigger. It will however still not trigger past my print and use, area.on_hit() from the mushroom script:
func _on_hitbox_area_entered(area):
print("on area entered")
if area.is_in_group("hit"):
area.on_hit()
Final solution: I changed on_body_entered, now it can interact. In order to use the method, i used area.has_method("on_hit"), rather than area.is_in_group. It now works! If someone can explain, why it doesn't work with body_entered and is_in_group, I'd really appreciate it for future development :)
Upvotes: 0
Views: 117
Reputation: 1
I changed on_body_entered
to on_area_entered
, now it can interact.
In order to use the method, I used area.has_method("on_hit")
, rather than area.is_in_group
.
It now works!
If someone can explain, why it doesn't work with body_entered
and is_in_group
, I'd really appreciate it for future development :)
Upvotes: 0