views:

123

answers:

1

Im getting straight to the point. I have static coordinates stored as array and i want to compare this coordinates with user 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)

but right now im stuck here coz i dont know how to structure my codes and i want to compare 3 save location touches to user touches so that when they hit the right spot points/score will be added but when they hit the wrong spot life will be deducted. Thanks.

+1  A: 

Hi,

If you had points stored like this . . .

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

try something like this :

// 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");

where distanceBetween is a function that looks something like (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);
}

Hope that helps,

Sam

deanWombourne
Thanks sam. just wondering is distanceBetween a better option than CGrectContainPoints when it comes to this kind of program. Thanks again.
Drahc
Hi,There's two reasons why I'd use the distance instead of the rect1) The corners of your rect will be too far away from the touch point but still count as a touch 2) Your code put the touch at the top left corner of the rect so you were only detecting touches down and to the right of the point.However, if you stored CGRect instead of CGPoint to compare against that would probably be fine :)
deanWombourne
Thanks dean i've already found a solution to this and i ended up using CGRectContainPoints and use if/else to compare set of touches.
Drahc