NoNaMe
NoNaMe

Reputation: 1

How to make Area2D keep track of body entry all the time?

sorry for my bad english. I have a problem. I need to make Area2D keep track of body entered all the time but it did it one time. How i can track this?

Code that i tried to use:

var hp = 10
var hero_in_me = false

func _physics_process(delta):
    if hero_in_me == true:
      hp -= 1
      print(hp)

func _on_Area2D_body_entered(body):
    if body.name == "Hero":
       hero_in_me = true

Upvotes: 0

Views: 903

Answers (1)

Theraot
Theraot

Reputation: 40220

I'm not sure what you mean by "all the time", given that the "body_entered" signal notifies you when the body entered. So, either you want to know all the time the body is inside, or you want to register when the body exited and entered again.

Either way, you would, of course, need to handle when the body exists the Area2D, so you know when the body is no longer inside.

Assuming the "body_entered" signal is connected to _on_Area2D_body_entered and the "body_exited" signal is connected to _on_Area2D_body_exited, you could do this:

var hero_in_me = false

func _on_Area2D_body_entered(body):
    if body.name == "Hero":
       hero_in_me = true

func _on_Area2D_body_exited(body):
    if body.name == "Hero":
       hero_in_me = false

And there you can check for hero_in_me.

Or like this:

var hero = null

func _on_Area2D_body_entered(body):
    if hero == null and body.name == "Hero":
       hero = body

func _on_Area2D_body_exited(body):
    if body == hero
       hero = null

And there you can check for hero != null. And you also have the reference if you need to call into it.

Or if you want to keep track of all the bodies that enter the Area2D, you can store them in an array:

var bodies_inside := []

func _on_Area2D_body_entered(body):
    bodies_inside.append(body)

func _on_Area2D_body_exited(body):
    bodies_inside.erase(body)

Then to check if a particular body is inside, you could check bodies_inside.has(body). You could also loop over the array to access all the bodies.

Upvotes: 1

Related Questions