+1 vote

I came across a really strange quirk today while coding a "shield" health system:

var Armor = 50.0

func _ready():
    damage(50.0)

func damage(amount):
    Armor -= amount * 2 / 3

This sets armor to the expected value (~16.66), however:

func damage(amount):
    Armor -= amount * (2 / 3)

This does not subtract anything from the armor. Armor remains at 50.

I prefer to have my fractions formatted in parentheses for more readable code. Why does this make a difference?

in Engine by (16 points)

1 Answer

+3 votes
Best answer

This is about integer division. 2 / 3 == 0 while 2.0 / 3.0 = 0.6667

The reason the first version works is because of order of operations. amount * 2 results in a float, so dividing by 3 results in the expected value.

As long as one of the operands is a float, then the result will be a float, so you can do:

Armor -= amount * (2 / 3.0)
by (20,893 points)
selected by

Duh! I can't believe I forgot about that. I just needed a fresh pair of eyes on 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 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.