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 (399 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_wait_time(0.25) # 0.25 is just an example. 
    timer.connect("timeout", self, "health_decrement")

In the area2d script,

timer = get_node("player/timer")

func on_area_body_enter(body):

func on_area_body_exit(body):

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

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 (842 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 Frequently asked questions and 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 [email protected] with your username.