0

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)

4

2 回答 2

0

浮点等式从来都不是精确的,当涉及到数学时,这可能变得越来越重要(它可以通过微小的数量改变数字的精确表示)。

一般不要将“==”用于浮点数;编写一个近似相等的函数(选择一些微小的值,如 0.001 并查看目标值是否在该数值的正负范围内)。

于 2013-11-18T18:33:41.223 回答
0

终于找到了我的解决方案(一直在从事其他项目,实际上并没有花这么长时间),只需将 .5 添加到我的位置,然后将其转换为 int。

所以我把它写成

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

它就像一个魅力:)

于 2013-12-16T22:51:50.483 回答