2013-12-16 58 views
0

我可能已经开始太久了,根本看不到逻辑问题。我正在改变平底锅手势的背景图像。通过背景和循环的图像名称数组左右循环。数组索引中的逻辑问题

滑动右(增加)工作正常,它循环回到我的数组的开始。 向左滑动即可(减少在第一对象停止在我的数组(objectIndex:0)

NSLog(@"_imageBackgroundIndex Before:%d",_imageBackgroundIndex); 

if ([_panDirection isEqual:@"Right"]) 
{ 
    _imageBackgroundIndex = _imageBackgroundIndex + 1; 
} 

if ([_panDirection isEqual:@"Left"]) 
{ 
    _imageBackgroundIndex = _imageBackgroundIndex - 1; 
} 


NSLog(@"_imageBackgroundIndex After:%d",_imageBackgroundIndex); 

if (_imageBackgroundIndex > ([_backgroundImages count] - 1)) 
{ 
    _imageBackgroundIndex = 0; 
} 

if (_imageBackgroundIndex < 0) 
{ 
    _imageBackgroundIndex = ([_backgroundImages count] - 1); 
} 


[[self childNodeWithName:kBackgroundName] runAction: 
    [SKAction setTexture: 
     [SKTexture textureWithImageNamed: 
      [_backgroundImages objectAtIndex:_imageBackgroundIndex]]]]; 

任何人看到这个问题

回答

0

代码看起来不错(虽然有一些风格的改进考虑,一旦你得到什么?它的工作)。我敢打赌,你有_imageBackgroundIndex声明为unsigned intNSUInteger。当你认为它降到零,它确实承担了巨大的无符号值。

这段代码就可以了(并具有较好的风格)即使计数器被声明为无符号...

- (void)incrementIndex { 
    BOOL increment = self.imageBackgroundIndex < self.backgroundImages.count-1; 
    self.imageBackgroundIndex = (increment)? self.imageBackgroundIndex+1 : 0; 
} 

- (void)decrementIndex { 
    BOOL decrement = self.imageBackgroundIndex > 0; 
    self.imageBackgroundIndex = (decrement)? self.imageBackgroundIndex-1 : self.backgroundImages.count-1; 
} 

那么你的盘法变得更简单:

// not sure how panDirection is initialized, is it really a string @"Left" or @"Right"? 
// if so, use isEqualToString to compare strings 

if ([_panDirection isEqualToString:@"Right"]) [self incrementIndex]; 
else if ([_panDirection isEqualToString:@"Left"]) [self decrementIndex]; 

[[self childNodeWithName:kBackgroundName] runAction:// ... etc