Having Issues with Counters in the _physics_process in Godot 4.2.1

Godot Version

4.2.1

Question

Hey everyone, I’m having issues with counters in the _physics_process function. For some context, I’m trying to prototype acceleration and deceleration in a player’s movement. I’m using a tickUp counter for acceleration and a tickDown counter for deceleration. I’m using an if statement to check to see if the tickUp counter is not equal to one. Once the tickUp counter is one, the tickUp counter will no longer be increment. But the problem is, the if statement never results in false. The tickUp counter will continue to increment no matter what. Here is my code. I’m an experienced programmer, but I’m new to game dev. Is this a bug, is my code off, or am I fundamentally misunderstanding the _physics_process function?

Here is my isolated _physics_process function. If you would like my entire script, I will post it.

Try declaring @onready var tickUp = 0.0, that is declared as an int, not a float

Tried your solution, and it didn’t work. I even declared the data type of var with : float, and it didn’t work. In the conditional statement, I made it a 0.0 too, and still results in a true.

You should check tickUp < 1.0 instead, it’ll never be exactly 1.0

I think the issue here is how you’re checking if a Vector2 (direction) is close to zero. While using simple comparisons like == 0 might seem straightforward, there’s a better approach.

The problem lies in computers way of handling numbers. They use a system called “floating-point,” which can introduce tiny inaccuracies during calculations. Imagine subtracting two very close numbers – the result might not be exactly zero due to rounding errors.

Here’s where direction.is_zero_approx() comes in. This built-in Godot function helps address these floating-point issues. It allows you to specify a tolerance level, essentially defining how close a value needs to be to zero to be considered “zero” in your code.

Use better the built-in function .is_zero_approx() when it comes to check if a Vector it’s near to zero.

if direction.is_zero_approx():
      velocity = Vector2.ZERO
else:
  ## Your tick stuff
1 Like

I was just about to post my solution lol. I decided to use the < comparator instead of the !=. The < comparator ended up working, so you’re right about the floating point inaccuracies. I can’t believe it took me this long to realize this. I appreciate your help in identifying this, though!

1 Like