0
votes

I'm making a game in iOS using Cocos2d.

This is the method Im using to check to see if a cube has been touched,

- (void)selectSpriteForTouch:(CGPoint)touchLocation {
    CubeSprite * newSprite = nil;
    for (CubeSprite *sprite in movableSprites) {
        NSLog(@"tested against sprite %i", sprite.boundingBox.origin.x);
        if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {      
            singleCube = true;
            newSprite = sprite;
            activeTag = sprite.tag;
            break;
        }
    }    
    if (newSprite != selSprite) {

        selSprite = newSprite;
    }
}

But for some reason, the sprite.boundingBox isn't being set correctly.

The "tested against sprite" log just prints out "test against sprite 0", which doesn't seem possible as I can see the sprite on my screen.

Here's the method that I use to add the cube to my scene,

-(void)addCube:(CubeSprite *)cube {
    int totalCubes = [cubes count];
    [cube setPosition:ccp(700 - (totalCubes * 50), 120)];
    [cubes addObject:cube];
    [movableSprites addObject:cube];
    [self addChild:cube];
}

What could possibly be wrong?

Thanks in advance.

Edit, here is my cube init method

-(id)initWithNumber:(int)number {
    if( (self=[super init])) {
        [self setTag:number];
        CCSprite* sprite = [CCSprite spriteWithFile:string];
        [self addChild:sprite];
        NSLog(@"Cube created with value of %i and with file %@", number, string);
    }
    return self;
}
3

3 Answers

0
votes

try to use this

 for (CubeSprite *sprite in movableSprites) {
CGRect projectileRect = [sprite boundingBox];

if (CGRectContainsPoint(projectileRect, touchLocation)) {      
            singleCube = true;
            newSprite = sprite;
            activeTag = sprite.tag;
            break;
        }
    }    
0
votes

Maybe CGRectContainsPoint returns false possitive. If you disable the "break ;" statement, it should iterate through all the cubes.

Some things that could be wrong : - cube's boundingbox is too large and position is not where you think - all cubes have the same position - touchLocation is (0,0)

0
votes

Didn't Xcode give you a warning about incorrect format string?

NSLog(@"tested against sprite %i", sprite.boundingBox.origin.x);

%i means integer value. CGPoint's coordinates are floating point values. Use %f instead.