Divide two variables to get a third

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


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 xp_next_level 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!

:bust_in_silhouette: Reply From: jgodfrey

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)

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.

Zach1812 | 2020-04-28 00:50