Search code examples
iosobjective-cclasscocos2d-iphonespritebuilder

Multiple objects of the same class reference only one of the objects


I'm using SpriteBuilder to design levels for a game. In the game, I have a block object that moves when swiped. However, when I have more than one of those objects in the level, each one only references the last one added. They all get initialized as unique objects, but when I swipe, they don't move. The only one that works correctly is the last one added to the level.

The swipe gestures are here.

- (void)didLoadFromCCB {
// Listen for swipe gestures to the right and left
UISwipeGestureRecognizer * swipeRight= [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeRight)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[[[CCDirector sharedDirector] view] addGestureRecognizer:swipeRight];

UISwipeGestureRecognizer * swipeLeft= [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeLeft)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[[[CCDirector sharedDirector] view] addGestureRecognizer:swipeLeft];
}

And here is one of the swiping methods that logs the wrong object as self. I also have a touch began method that is logging the correct object.

- (void)swipeRight {

// Only move the object if it is being touched while swiping
CCLOG(@" Swipe right %@", self);
if (self.touched) {
    // Move the object off the screen to the right
    float width = [self parent].contentSizeInPoints.width;
    [self swipeOffScreen:ccp(self.position.x + width, self.position.y)];
}
}

Solution

  • Instead of using the swipeRight method, I took the code and moved it to a touchEnded method and set self.touched to true in the touchMoved. I believe the problem is the difference between the UIKit swipe wrapper and the Cocos2D touch methods.