Working with a variable

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By VarionDrakon

Such a difficult question, how to make a character invulnerable for 1 (or more) second after taking damage?

And also how to limit the range of variable changes, for example, so that it does not rise above 70?

:bust_in_silhouette: Reply From: jgodfrey

One way (off the top of my head, untested…)

  • Add a Timer node to your scene
  • Set the timer’s OneShot property to true
  • Set the time’s 'WaitTime` to 1 (so, wait for 1 second)
  • Add a var invulnerable = false to your scene script as a global variable
  • Wrap the code where your player takes damage with an if that checks the new var
    if damage_taken && !invulnerable:
        invulnerable = true
        # do remaining damage code here
  • Wire theTimer’s timeout event to this script
    func _on_Timer_timeout():
        inuvlnerable = false

With that, when the player starts to take damage, the invulnerable flag will be set, and it’ll stay set until the timer times out (1 second). At that point, the invulnerable flag will be unset, and the player can take damage again.

Can I use C# without any “Nodes”?

VarionDrakon | 2020-11-19 18:43

For the question about limiting the range of a variable (though, really, you should ask it separately)…

You’re probably looking for the clamp() function, which will limit a value to be within a specified range. For example, if you wanted something between 0 and 70…

my_val = float clamp (my_val, 0, 70)

That will return:

  • The original value if it falls between 0 and 70
  • 0 if the value is less than 0
  • 70 if the value is greater than 70

See the docs for details:

@GDScript — Godot Engine (stable) documentation in English

jgodfrey | 2020-11-19 18:44

Can I use C# without any “Nodes”?

I don’t understand what you’re asking here…

jgodfrey | 2020-11-19 18:46

I’m talking about time invulnerability…

VarionDrakon | 2020-11-19 18:46

So, no Timer node? Yeah, you can do it without a timer node. Really, you just need a way to keep track of the 1 second delay. You could do that by tracking it yourself in (for example) the _process()function.

Just add the delta value to a running accumulator until it reaches your limit (1 second)…

While somewhat more difficult than a simple timer, it would work just as well…

jgodfrey | 2020-11-19 18:49

Yes, I’m asking about “time Invulnerability” so that you can implement it in C# without “Nodes”.

VarionDrakon | 2020-11-19 18:50