iOS - Drag and drop collision detection How to det

2020-05-21 05:07发布

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]]; 
  }
}

2条回答
Luminary・发光体
2楼-- · 2020-05-21 05:38

Also might want to consider view.center with CGRectContainsPoint()

查看更多
The star\"
3楼-- · 2020-05-21 05:56

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.

查看更多
登录 后发表回答