【发布时间】:2011-03-17 14:29:23
【问题描述】:
我正在制作一个 UIImageView(ball) 在 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");
}
【问题讨论】:
标签: xcode drawing collision-detection paint