在我的项目中,我想让用户触摸屏幕并在他移动时画一条线。
我还想确保用户不会与他之前绘制的任何现有线(包括同一条线本身)相交。
我四处搜索线交叉算法或函数,但它们太复杂了,性能也不好。所以,我想到了另一种方法。通过设置背景和线条的颜色不同,如果我可以读取当前触摸点的颜色,那么我可以将它与线条颜色进行比较,看看是否确实发生了任何交叉。
我尝试使用 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);
}
}