1

I have two variables, a speed and a minimum. The speed gets compared to the minimum to see if the speed should continue decreasing. For some reason, even when the speed is equal to the minimum, it continues to decrease the speed.

var wallSpeed       : CGFloat!
var wallSpeedMin    : CGFloat!
var wallSpeedChange : CGFloat!

override init(){
    wallSpeed         = 0.0035
    wallSpeedMin      = 0.0034
    wallSpeedChange   = 0.0001
}

The speed minimum is close to the speed for testing purposes.

if wallSpeed > wallSpeedMin
    {
        print("Wall speed has been increased")

        wallSpeed = wallSpeed - wallSpeedChange

        print("New speed is \(wallSpeed!)")
    }else
    {
        print("Player moved up screen")

        //Move player up instead
        playerNode.position.y = playerNode.position.y + 5

        print("Players Y value is \(playerNode.position.y)")
    }

It never hits the else statement, even though the wall speed is equal to the wall speed minimum after the first decrease.

Do I have my if statement set up incorrectly? What is causing this behavior?

Joseph Kessler
  • 93
  • 2
  • 11

2 Answers2

1

Floating point math does not work like you're expecting it to. Check Is floating point math broken?

Gereon
  • 17,258
  • 4
  • 42
  • 73
0

You can't compare floating point numbers like this way...

Since the way of the floating point number represented we can't simply do some math on them....

when we use integers they are represented directly in binary format, and you can do any arithmetic calculation on them, while floating point numbers are 32 bits container following the IEEE 754 standard divided in three sections :

1 bit S for the sign

8 bits for the exponent

23 bits for the mantissa

For more information Comparing Floating Point Numbers and Floating Point in Swift

mojtaba al moussawi
  • 1,360
  • 1
  • 13
  • 21