CGrectContainPoints&接触查询

时间:2009-11-05 09:55:41

标签: iphone coordinates touch

我直言不讳。我有静态坐标存储为数组,我想比较这个坐标与用户触摸。

//touch handling
 UITouch *touch = [[event allTouches] anyObject];
 CGPoint touchPoint = [touch locationInView:touch.view];
//comparing touches
 if (CGRectContainsPoint((CGRectMake(x1, y1, w, h)) , touchPoint)) {
  // do something
            // this is where i got stuck coz i got 2 more sets of x & y. (x2-y2 & x3-y3)

但是现在我卡在这里因为我不知道如何构建我的代码,我想比较3个保存位置触摸到用户触摸,这样当他们点击正确的点点/分数将被添加但是当他们遇到错误现场生活将被扣除。感谢。

1 个答案:

答案 0 :(得分:1)

如果您有像这样存储的点数。 。

CGPoint p1 = CGPointMake(100,100);
CGPoint p2 = CGPointMake(200,200);

尝试这样的事情:

// Get the location of the user's touch
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView:touch.view];

float maxDistance = 10;

// Is it in the right place?
if (distanceBetween(touchPoint, p1) < maxDistance)
  NSLog(@"touched point 1");
else
if (distanceBetween(touchPoint, p2) < maxDistance)
  NSLog(@"touched point 2");

其中distanceBetween是一个类似于(some maths

的函数
// Distance between two CGPoints
float distanceBetween(CGPoint p1, CGPoint p2) {
  float dx = p1.x-p2.x;
  float dy = p1.y-p2.y;
  return sqrt( dx*dx + dy*dy);
}

希望有所帮助,

萨姆