ganesh
ganesh

Reputation: 166

Get color of background in cocos2d/IOS

In my project, I want to let user touch the screen & a line will be drawn as he moves across.

I also want to make sure that user doesn't intersect with any existing line which he drew before (including same line itself).

I searched around for line intersection algorithms or functions but they are too complex and performance wise also they aren't good. So, I thought of another way to do it. By setting color of background and line different, if I can read the color of current touch point, then I can compare it with line color and find out if any intersection does happen.

I tried using glReadPixel method but it's returning Green color for all touch points which is not set to either background or lines. My background is default color (black) and lines are default white. All lines are drawn in same layer. I haven't drawn background as a seperate layer. Just using defaults.

    -(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    CCLOG(@"touch moved");
    UITouch* touch = [touches anyObject];
    CGPoint currentTouchPoint = [touch locationInView:[touch view]];
    CGPoint lastTouchPoint = [touch previousLocationInView:[touch view]];

    currentTouchPoint = [[CCDirector sharedDirector] convertToGL:currentTouchPoint];
    lastTouchPoint = [[CCDirector sharedDirector] convertToGL:lastTouchPoint];

    CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:1 height:1];
    [renderTexture begin];
    [self visit];
    Byte pixelColors[4];
    glReadPixels(currentTouchPoint.x, currentTouchPoint.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixelColors[0]);
    [renderTexture end];
    CCLOG(@"pixel color: %u, %u, %u", pixelColors[0], pixelColors[1], pixelColors[2]); 


    CCLOG(@"last a=%.0f, b=%.0f", lastTouchPoint.x, lastTouchPoint.y);
    CCLOG(@"Current x=%.0f, y=%.0f",currentTouchPoint.x, currentTouchPoint.y);
    [touchPoints addObject:NSStringFromCGPoint(currentTouchPoint)];
    [touchPoints addObject:NSStringFromCGPoint(lastTouchPoint)];
}

-(void)draw{
    CGPoint start;
    CGPoint end;
    glLineWidth(4.0f);
    for (int i=0; i<[touchPoints count]; i=i+2) {
        start = CGPointFromString([touchPoints objectAtIndex:i]);
        end = CGPointFromString([touchPoints objectAtIndex:i+1]);
        ccDrawLine(start, end);
    }
}

Upvotes: 0

Views: 310

Answers (1)

CodeSmile
CodeSmile

Reputation: 64477

You can only use OpenGL methods (glReadPixels here) in either the draw or visit methods. That's most likely why you get green all the time.

Within a render texture's begin/end method you can only access the render texture, not the frame buffer.

Upvotes: 1

Related Questions