Xcode - 用户绘制的线条碰撞检测

时间:2011-03-17 14:29:24

标签: xcode drawing collision-detection paint

我制作了一个游戏,其中UIImageView(球)在iphone屏幕的边缘随机弹跳。然后用户必须用他们的手指画线以将球引导到洞/目标中。我已设法实现随机弹跳球和绘制到屏幕上的能力。我的问题是,我不能让我的生活在球和用户绘制的线之间检测到碰撞。球刚穿过它。我曾尝试使用CGRectIntersectsRect但我很确定这种方法不起作用。我基本上想要的是让球从用户绘制线上反弹的某种方式。如果有人知道如何做到这一点,可以帮助我将非常感激。

提前致谢

我添加了一些代码,试图帮助你们了解我的设置。

触摸开始是用户首先将手指放在屏幕上的地方

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {  

fingerSwiped = NO;
UITouch *touch = [touches anyObject];
lastPoint = [touch locationInView:self.view];
startPoint = [touch locationInView:self.view];
lastPoint.y -= 0;

}

触摸移动是指手指在屏幕上移动

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

fingerSwiped = YES;
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
currentPoint.y -= 0;
UIGraphicsBeginImageContext(self.view.frame.size);

[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width,                    self.view.frame.size.height)];

CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);

// sets the width of the line
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
//sets the colour of the line drawn

//red
//CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
//green
//CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 1.0, 0.0, 1.0);
//blue
//CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 1.0, 1.0);
//black
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
//draws a line to the point where the user has touched the screen
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

lastPoint = currentPoint;

fingerMoved++;

}

这是我目前正在尝试用于实际的碰撞检测......

float a = lastPoint.y - startPoint.y;
float b = startPoint.x - lastPoint.x;
float c = lastPoint.x * startPoint.y - startPoint.x * lastPoint.y;
float d = abs(a * ball.center.x + b *ball.center.y + c)/sqrtf(powf(a,2)+ powf(b,2));

if(d ==0){
    NSLog(@"collision detected");

}

2 个答案:

答案 0 :(得分:1)

我不知道Xcode,但是,可能这两个绘制的对象(球和线)共享一些坐标空间。我假设球有一个位置和一个半径,并且该线有一些终点。在将球从任何地方移动到下一帧中的任何位置之前,您“测试”建议的新位置以查看圆圈是否已触及该线。如果线是“无限的”,或者至少是走出屏幕边缘,那么两个物体之间最接近的方法将是将圆心连接到线并且垂直于该线的线。垂直线的斜率是原始线的-1 * 1 / m(其中m是斜率)。您可以从圆的中心开始绘制具有该斜率的测试线,并计算测试线与用户绘制线的交点与某些代数的位置。然后只计算该段的长度,如果它短于球的半径,则你就到了该线。

如果线与球相比是一个短线段,您可以沿线选择几个点并直接测试球的中心,再次比较中心到半径的距离。

答案 1 :(得分:1)

请发一些代码。

时间对于碰撞检测非常重要,您可能不会在正确的时间提出问题。首先测试你的代码。制作一个球和一条线,明确地对准你的探测器。如果它测试正确,那么很可能与在正确的时间不问“这些物体是否碰撞”有关。

相关问题