2013-03-16 86 views
0

在我的項目中,我想讓用戶觸摸屏幕&當他移動時會畫出一條線。在cocos2d/IOS中獲取背景顏色

我也想確保用戶不會與他之前繪製的任何現有線相交(包括同一線本身)。

我搜索周圍的線交集算法或函數,但它們太複雜,性能也很不好。所以,我想到另一種方式來做到這一點。通過設置背景和線條的顏色不同,如果我可以讀取當前觸點的顏色,則可以將其與線條顏色進行比較,並確定是否發生任何交點。

我嘗試過使用glReadPixel方法,但它對所有未設置爲背景或線條的接觸點返回綠色。我的背景是默認顏色(黑色),線條默認爲白色。所有線都繪製在同一圖層中。我沒有把背景作爲一個單獨的層。只使用默認值。

-(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); 
    } 
} 

回答

1

您只能使用無論是在平局或訪問方法OpenGL的方法(glReadPixels這裏)。這很可能是你爲什麼總是變綠的原因。

在渲染紋理的開始/結束方法中,您只能訪問渲染紋理,而不能訪問幀緩衝區。

+0

你的意思是我應該在我的繪製方法中移動glReadPixel調用?這將觸發讀取每幀畫面上的像素。對性能不壞?截至目前,我在繪製方法下繪製線條。在哪裏以及如何放置glReadPixel調用?謝謝你的幫助 !!! – ganesh 2013-03-17 06:36:56

+0

謝謝,它是在我將glReadPixel移入draw方法後工作的。 – ganesh 2013-03-19 01:54:56