0 votes

Example i make an area that keeps damaging the player as long he is in it how do i do that do i need a for or while loop for it

in Engine by (395 points)

2 Answers

+2 votes

I don't know how you can do that using a for/while loop but I think timers should work.
In the player script,

timer = null
health = 1000

func health_decrement():
    health -= 50 # Amount to decrement from health in 0.25 secs

func _ready():

    timer = Timer.new()
    timer.set_one_shot(false)
    timer.set_wait_time(0.25) # 0.25 is just an example. 
    timer.connect("timeout", self, "health_decrement")
    add_child(timer)

In the area2d script,

timer = get_node("player/timer")

func on_area_body_enter(body):
    timer.start()

func on_area_body_exit(body):
    timer.stop()

This should work!

by (418 points)

Another option:

On fixed/physics process check for overlapping bodies and apply your damage there (this means constant overlapping body checks).

And you do not need a loop, the game loop does that for you.

@eons I agree.

can you give an example pls

+2 votes

I would follow the advice of eons.

Here's an example on how to do that in code:

func _physics_process(delta): # get's called every physics step
     if Area2D.overlaps_body(PhysicsBody2D): # returns bool true/false
        damage_player()

if you're writing that code in the Area2D node, you won't need to call the function explicitly on the object (as in self.call() like with other languages).

by (840 points)

I was considering this while writing my answer. I am still kind of a noob in Godot but have you considered frame-rates. Won't devices with higher frame-rates 'damage_player()' quicker than other devices? Or will it not?

You can suffer the fate of some AAA games at different framerates if using regular process, physics process is usually locked at 60 fps, but yes, a safe option could be to do damage_player(raw_damage_per_second/delta).

@eons Got it! Thanks!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.