0

In this code, one of my sprites should reduce speed until it meets 0.75. However, once the code does get to 0.75, it keeps reducing for some reason. I have a timer which calls the speed_Control func every 0.2 seconds and the sprite.speed starts at 1.0.

func speed_Control() {
    if boolDecrease == true {
        speed_Decrease()
    }
}

func speed_Decrease() {
    if sprite.speed != 0.75 {
        println(sprite.speed)
        sprite.speed -= 0.05
    } else {
        boolDecrease = false
    }
}

I added println(sprite.speed) to see if my sprite does actually ever return 0.75, which it does, so I don't know how it passes if sprite.speed != 0.75.

Can anybody see what is wrong with this?

Jarron
  • 1,049
  • 2
  • 13
  • 29
  • 1
    You should read this http://stackoverflow.com/questions/10334688/how-dangerous-is-it-to-compare-floating-point-values – 0x141E Sep 13 '15 at 06:51
  • Thanks for the link, this has given me a better understanding why floats are not exact. Thank you. – Jarron Sep 13 '15 at 07:00

1 Answers1

4

Floating-point values should not be compared using (in)equality operators. The value 0.05 cannot be exactly represented, so speed will end up being something close to, but not exactly equal to 0.75. A simple solution here would be to change the condition sprite.speed != 0.75 to sprite.speed > 0.76.

feersum
  • 658
  • 4
  • 11