0
votes

I'm using SpriteKit and working on a system of moving SKSpriteNodes around the screen. I have two global variables that are set before the moving method is called: positionAndMovementX and positionAndMovementY which I have tried as both integers and floats. Before the method that moves my SKSpriteNode is called, both of these variables will be set to either 0, 80, or -80. Then I run:

 if (emptySpace.position.x == yellowBug.position.x + positionAndMovementX && 
 emptySpace.position.y == yellowBug.position.y + positionAndMovementY)
 {
      SKAction *moveLeft = [SKAction moveByX:positionAndMovementX y:positionAndMovementY duration:.1];

      [yellowBug runAction: moveLeft];
 }

Unfortunately, this will work for several movements, but after 5 or so, either the x or the y value will become inexact and decrease or increase by .000015 or something, so now instead of being 200, 180, its 200, 179.999985, and my equation wont evaluate anymore. I tried changing the position to an integer and back, but 179.999985 was changed to 179 instead of 180 for some reason, so i tried rounding as follows:

int posX = lroundf(yellowBug.position.x);
int posY = lroundf(yellowBug.position.y);

[yellowBug setPosition:CGPointMake(posX, posY)];

but this just seems to leave the variable at 179.999985 again... Help? (sorry if this is a noob question, im still a beginner)

2

2 Answers

0
votes

Floating-point equality is never exact, and this is increasingly likely to matter when math is involved (which can change the precise representation of a number by tiny amounts).

Don't use "==" for floats, generally; write a function that does approximate equality (choosing some tiny value like 0.001 and seeing if a target value is within plus-or-minus that amount).

0
votes

FINALLY found my solution (been working on other projects, didnt actually take this long) by simply adding .5 to my position and THEN casting it to an int.

so I write it as

if ((int)(yellowBug.position.x + .5) == yada yada)

and it works like a charm :)