0 votes

When Light2D energy set to 0.5
Light2D's script:

extends Light2D

var se = 0

func _physics_process(delta):
    check()

func check():
    se = self.energy
    if se == 0.5:
        print(1)
    else:
        print(0)

Output:

1
1
1

BUT when energy set to 0.7

extends Light2D

var se = 0

func _physics_process(delta):
    check()

func check():
    se = self.energy
    if se == 0.7:
        print(1)
    else:
        print(0)

Output:

0
0
0

Values of 0.6, 0.7, 0.8, and 0.9 results in the same. The debugger shows no error as well. What am I missing?

Godot version v3.3.2
in Engine by (12 points)

1 Answer

+1 vote

It might be floating point issue, because there are infinite number of values between any two float numbers. This is the reason why float values are stored with some precision. Try to check your values with some tolerance, i.e. instead of writing

if se == 0.7:

try

if (se - 0.7) < 0.001:
by (1,650 points)

Godot has built-in is_equal_approx() and is_zero_approx() functions for this. You don't need to use a manual epsilon value most of the time.

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 Frequently asked questions and 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 [email protected] with your username.