Int can't seem to drop below 0 for unknown reason

Godot Version

4.2.1

Question

There’s a challenge in my game where you have to hold a key, or combination of keys, down for a few seconds in order to make something happen. If you hold it down for too long, I want the challenge to fail. With that in mind, it needs to be possible for the countdown timer to be a negative number (or, I guess, it doesn’t need to be possible, but it would be more intuitive if it were).

I declare an int for this outside my methods like so:

var component_A_amount:int

I initialize it in a custom init function like so:

var random = RandomNumberGenerator.new()
random.randomize()
component_A_amount = random.randi_range(100, 200)

Then I’m doing this in process:

if active_keypresses.has(component_A_key):
component_A_amount -= (delta * component_depletion_rate)

This works exactly how you’d expect until component_A_amount reaches zero. Then it just stops decrementing, and returns 0 every time process is called. Is there something weird about how I declared or initialized the int? I just can’t think of any other reason for it to do this.

Thank you for any help!

Have you used the debugger before?

If not, I think this would be a perfect opportunity to learn how. (Not being snarky, I can help you)

If you have used the debugger, what did you see?

1 Like

I think it’s because (delta * component_depletion_rate) will be a float, and you’re substracting that from an int.
For example if (delta * component_depletion_rate) is 0.1:
1 - 0.1 = 0.9 which will be 0 as an int, so you started with 1 and after substracting you have 0, so what you’d expect.
But
0 - 0.1 = -0.1 which will be still 0 as an int, not -1.

The easiest fix would be to make component_A_amount a float, if that works.

2 Likes

That sounds right to me.

That did work, thank you so much!

1 Like

Oh, interesting, I haven’t, but I’m googling it now. Thanks for the tip!

It is super easy to use for something like this.

Just click the line where you think the problem is to set a breakpoint. (Click on the left, it should make a red circle)

When you run your code, it will stop there.

There will be a part of the screen where you can click on each vatiable to see what is stored in it.

Then you can advance it on line at a time (step in or step over, depending) and see how the values change.

From there you can at least pinpoint the exact point the code does something other than what you expected (and a few details about what it is doing instead).

Careful on “step in” as it can take you into code you didnt write (eg a plugin or anything else)

Thanks for this! I poked around and never knew you could check one box to turn all your collision nodes visible, extremely helpful.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.