Cocos2d:批量精灵的像素完美碰撞

时间:2012-10-22 08:43:01

标签: ios cocos2d-iphone collision-detection pixel

我找到了Daniel Vilchez开发的像素完美碰撞算法,该算法包含在共享in this cocos2d-iphone.org forum topic的项目中。

下面是我感兴趣的算法部分。我试图修改这个,因为每当我使用CCRenderTexture时,就像代码中最初的那样,App崩溃了。

我正在考虑alternative methods based on circle collision,但那些“不是像素完美”,如果我的子弹是this shape的波浪,它将无法正常工作。

**我想知道如何使用在CCSpriteBatchNode中批处理的精灵来运行算法?如果是这样,这严格包括CCRenderTexture的使用? **

准确地说,这个问题与this other question of mine部分相关,在创建导致我的App崩溃的CCRenderTexture实例时。我发布了两个不同的,因为我在这里询问算法,另一个我只是问为什么CCRenderTexture导致我的App崩溃(没有使用Daniel的像素完美算法,只是创建了CCRenderTexture的实例)。

改编的CODE(这里缺少CCRenderTexture,因为它让我的应用程序崩溃了,所以我注释掉了_rt的用法--CCRenderTexture的实例)。代码不能正常工作,所以我想我需要CCRenderTexture,因此我问了一个问题:

-(BOOL) isPixelPerfectCollisionBetweenSpriteA:(CCSprite*)spr1 spriteB:(CCSprite*) spr2
{
    BOOL isCollision = NO; 
    CGRect intersection = CGRectIntersection([spr1 boundingBox], [spr2 boundingBox]);

    // Look for simple bounding box collision
    if (!CGRectIsEmpty(intersection))
    {
        // Get intersection info
        unsigned int x = intersection.origin.x;
        unsigned int y = intersection.origin.y;
        unsigned int w = intersection.size.width;
        unsigned int h = intersection.size.height;
        unsigned int numPixels = w * h;

        //NSLog(@"\nintersection = (%u,%u,%u,%u), area = %u",x,y,w,h,numPixels);

        // Draw into the RenderTexture
        //[_rt beginWithClear:0 g:0 b:0 a:0];

        // Render both sprites: first one in RED and second one in GREEN
        glColorMask(1, 0, 0, 1);
        [spr1 visit];
        glColorMask(0, 1, 0, 1);
        [spr2 visit];
        glColorMask(1, 1, 1, 1); 

        // Get color values of intersection area
        ccColor4B *buffer = malloc( sizeof(ccColor4B) * numPixels );
        glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

        //[_rt end];

        // Read buffer
        unsigned int step = 1;
        for(unsigned int i=0; i<numPixels; i+=step)
        {
            ccColor4B color = buffer[i];

            if (color.r > 0 && color.g > 0)
            {
                isCollision = YES;
                break;
            }
        }

        // Free buffer memory
        free(buffer);
    }

    return isCollision;

编辑:我发现KKPixelMaskSprite但它似乎不适用于在CCSpriteBatchNodes中批量处理的高分辨率精灵(请参阅此处的comment)。

0 个答案:

没有答案
相关问题