Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Drag and drop collision detection How to detect when your selected item drags over another subview?

We are adding drag and drop functionality to what is to become a sports field with positions for players.

The positions are mapped out using Interface Builder with each being a separate UIImageView.

We want to be able to drag player images from bench positions from the side of the screen onto positions on the field.

How best can we detect when the selected player which is being moved around collides with an existing gamePosition imageView?

We are looking for a way to detect if there is a view or ImageView under the current location.

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  UITouch *touch = [[event allTouches] anyObject];
  CGPoint location = [touch locationInView:touch.view];
  tile1.center = location;  

  if gamePositionExistsAtCurrentLocation(location) { //want something like this
    [tile1 setBackgroundColor:[UIColor blueColor]]; 
  } else {
   [tile1 setBackgroundColor:[UIColor yellowColor]]; 
  }
}
like image 509
Evolve Avatar asked Oct 16 '10 01:10

Evolve


1 Answers

check if the frame of the item you are moving intersects with the frame from on of your subviews

for (UIView *anotherView in self.subviews) {
    if (movingView == anotherView)
        continue;
    if (CGRectIntersectsRect(movingView.frame, anotherView.frame)) {
        // Do something
    }
}

If I were you, I would add all game relevant items to an NSArray and for-loop through this. So you don't detect collisions with subviews that have nothing to do with your game like labels and so on.

like image 156
Matthias Bauch Avatar answered Oct 27 '22 12:10

Matthias Bauch