用Cocos2D检查黑白(像素)

时间:2012-08-11 07:35:14

标签: iphone cocos2d-iphone

我正在尝试使用Cocos2D创建一个可破坏的世界,我对这个主题进行了一些阅读,但我无法弄清楚如何让它正常工作。

此刻我的测试非常简单;屏幕为黑色,触摸将使用CCRenderTexture在触摸的位置绘制一个白色圆圈。

这是我的测试:

// 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];
}

添加黑色背景后添加精灵:

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];

是否有一种简单的方法可以检查精灵是否在黑/白区域进行某种像素碰撞检查?

我以前见过这个问题,但答案总是如下:“如果是在黑色或白色区域,只需检查简单的黑/白图像”,好的,但是如何? :P

谢谢,

瑞克

1 个答案:

答案 0 :(得分:1)

如果您想进行像素碰撞检查,可在此处找到tutorial in 2 parts with code and references

一种替代方法可能是:

  1. 您使用CCRenderTexture进行渲染(正如您现在所做的那样);

  2. 而不是将CCRenderTexture添加到您的图层/父节点,您可以从中创建一个精灵:

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

    并将此项添加到您的图层/父级。

  3. 通过这样做,你将使用精灵表示所有爆炸,然后你可以进行碰撞检查。

    顺便说一下,在我建议的方法中,你为每次爆炸创建一个新的CCRenderTexture。

    另一种方法就是像现在这样做,即使用一个CCRenderTexture并在其中绘制所有内容,同时还保留一个爆炸CCNode列表(即,您还在您的图层中添加CCNode) /每次爆炸的父母)。然后你会在CCNodes上进行碰撞检测。