0
votes

I'm trying to create a destroyable world with Cocos2D and I did some reading on the subject, but I can't really figure out how to get it working properly.

I have a very simple test at the moment; the screen is black and a touch will draw a white circle on the touched location with CCRenderTexture.

This is my test:

// Get the black background

- (CCSprite *)sprite
{
    CGSize winSize = [CCDirector sharedDirector].winSize;
    self.renderTexture = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];
    [self.renderTexture beginWithClear:0.0 g:0.0 b:0.0 a:1.0];
    [self.renderTexture end];
    return [CCSprite spriteWithTexture:self.renderTexture.sprite.texture];
}

- (void)generateBackground
{
    background = [self sprite];

    CGSize winSize = [CCDirector sharedDirector].winSize;
    background.position = ccp(winSize.width/2, winSize.height/2);

    [self addChild:background z:-1];
}

// Draw the white circle

- (void)generateExplosionWithTouch:(UITouch *)touch
{
    [self.renderTexture begin];

    CGPoint location = [touch locationInView:touch.view];
    location = [self convertToNodeSpace:location];

    ccDrawCircle(location, 30.0, 5.0, 360, NO);

    [self.renderTexture end];
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [touches anyObject];
    [self generateExplosionWithTouch:touch];
}

I add a sprite after adding the black background:

CGSize winSize = [CCDirector sharedDirector].winSize;
self.icon = [CCSprite spriteWithFile:@"Icon.png"];
self.icon.position = ccp(winSize.width / 2, winSize.height / 2);
[self addChild:self.icon];

Is there an easy method to check if the sprite is on a black/white area with some kind of pixel collision check?

I've seen this question before, but the answer always was something like: "Just check with a simple black/white image if it's on the black or white area", ok, but how? :P

Thank you,

Rick

1

1 Answers

1
votes

If you want to do pixel collision check, here you can find a tutorial in 2 parts with code and references.

One alternative approach could be this:

  1. you use a CCRenderTexture to do the rendering (as you are doing now);

  2. instead of adding the CCRenderTexture to your layer/parent node, you create a sprite from it:

        return [CCSprite spriteWithTexture:renderTexture.sprite.texture];
    

    and add this one to your layer/parent.

By doing like this, you will have all of your explosions represented by a sprite, then you can do collision checking.

By the way, in the approach I suggest, you create a new CCRenderTexture for each explosion.

Another approach would be doing just like you are doing now, i.e., using one CCRenderTexture and draw everything inside of it, while at the same time also keeping a list of explosion CCNodes (i.e., you also add a CCNode to your layer/parent for each explosion). Then you would do collision detection on the CCNodes.