在我的项目中,我想让用户触摸屏幕&他移动时会绘制一条线。
我还想确保用户不会与之前绘制的任何现有线相交(包括相同的线本身)。
我搜索了线路交叉算法或函数,但它们过于复杂且性能明显,但它们并不好。所以,我想到了另一种方法。通过设置背景和线条的颜色不同,如果我可以读取当前触摸点的颜色,那么我可以将它与线条颜色进行比较,并找出是否有任何交叉点发生。
我尝试使用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);
}
}
答案 0 :(得分:1)
您只能在draw或visit方法中使用OpenGL方法(此处为glReadPixels)。这很可能是你一直变绿的原因。
在渲染纹理的开始/结束方法中,您只能访问渲染纹理,而不能访问帧缓冲区。