0 votes


I'm trying to do a bit of math inside one of my functions for my game. I have a TextureRect that expands when a variable is taken and multiplied by the number of pixels in the image. I've been following along with HeartBeast and his ARPG tutorials (This one being P18). Since I've changed much of the code he posted, I don't feel right asking him about this one issue. Here's what I want.

func set_xp(value):
     xp = clamp(value, 0, xp_next_level)
     var gained_xp = round((xp/xp_next_level)* 10)
     if xp_bar != null:
          xp_bar.rect_size.x = gained_xp * 3

What is supposed to happen is when the player kills a Snake, they receive 5 XP out of 10 XP. (5 XP for the kill, 10 XP to next Level). That would raise the xp_bar up to 50% completion.

When I do a print function inside the function, the xp and xpnextlevel come out correct (ie 5 and 10), but the gained_xp does not. It always returns a 0, no matter how much xp I give the player or what kind of math function I try.

I've even tried making xp and xp_next level integers within the math function but that doesn't solve the issue either.

Any help is greatly appreciated!

in Engine by (17 points)

1 Answer

+1 vote
Best answer

The problem is that all of the numbers involved are integers. Any math done on integers will always result in an integer. To fix the problem, you'll need to cast (at least) one of the values in the division to a float. So, this should work...

 var gained_xp = round((float(xp)/xp_next_level)* 10)
by (10,932 points)
selected by

This worked perfectly! Thanks. It’s funny. I’ve been pulling my hair out about this but when I figured out that the answer was always going to be a float, the solution you posted made so much sense.

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.