0 votes
if float(Lap.text) < float(Best.text):
    print("update Best")

The problem is when they are equal it still prints "update Best", when it only had to update when one is smaller. Numbers come with 3 decimals (eg: 13.578). When I print them they are exactly the same numbers, but it still says "update Best". What's the trick?

Edit: This didn't help either: if float(lapTime.text) - float(bestLap.text) < 0.000:

Godot version 3.2.3
in Engine by (307 points)
edited by

Floating point numbers are imprecise. You shouldn't use them for exact comparison.

Any alternative? - To compare numbers with decimals.

1 Answer

0 votes

I think you've got multiple issues here:

  • First of all, you're converting text back to a number, which is something you should avoid. Why not store the actual numbers?
  • You shouldn't have to constantly check whether the time has changed or is different. You know when it changes, so I'd absolutely go with signals instead.

This this from memory, so might include mistakes, but should give you a general idea on how I'd solve this (to be put into its own standalone script, e.g. score_tracker.gd):

extends Node
class_name ScoreTracker

signal highscore(best: float, previous: float)
var best: float
var first: bool = true
var inverted: bool

func reset() -> void:
    first = true

func track(score: float) -> void:
    if self.first or (self.inverted and self.best < score) or (self.best > score):
        self.first = false
        var previous = self.best
        self.best = score
        emit_signal("highscore", self.best, previous)

Once this is implemented, you can track scores using this new class:

var lap_tracker

func _ready() -> void:
    lap_tracker = ScoreTracker.new()
    lap_tracker.inverted = true
    lap_tracker.connect("highscore", self, "_on_highscore")

func _on_highscore(best: float, previous: float) -> void:
    # Update UI
    print("update Best")

# Whenever a lap finishes:
lap_tracker.track(time_as_float)

And yes, while this also ignores float imprecision, you shouldn't get repeated events, unless you indeed got a tad bit faster, even if it's just 1 microsecond.

by (216 points)
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.