Cocos2d 2.0 - Ignoring touches to transparent areas of layers/sprites

前端 未结 4 2104
一生所求
一生所求 2020-12-14 09:30

I have an app where I have several layers created from PNG images with transparency. These layers are all on the screen over each other. I need to be able to ignore touches

4条回答
  •  無奈伤痛
    2020-12-14 10:25

    Here you have a possible solution.

    Implement an extension on CCLayer and provide this method:

    - (BOOL)isPixelTransparentAtLocation:(CGPoint)loc 
    {   
        //Convert the location to the node space
        CGPoint location = [self convertToNodeSpace:loc];
    
        //This is the pixel we will read and test
        UInt8 pixel[4];
    
        //Prepare a render texture to draw the receiver on, so you are able to read the required pixel and test it    
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
        CCRenderTexture* renderTexture = [[CCRenderTexture alloc] initWithWidth:screenSize.width
                                                                         height:screenSize.height
                                                                    pixelFormat:kCCTexture2DPixelFormat_RGBA8888];
    
        [renderTexture begin];
    
        //Draw the layer
        [self draw];    
    
        //Read the pixel
        glReadPixels((GLint)location.x,(GLint)location.y, kHITTEST_WIDTH, kHITTEST_HEIGHT, GL_RGBA, GL_UNSIGNED_BYTE, pixel);
    
        //Cleanup
        [renderTexture end];
        [renderTexture release];
    
        //Test if the pixel's alpha byte is transparent
        return (pixel[3] == 0);
    }
    

提交回复
热议问题