Вопрос

I have written some code that restricts the movement of a box (UIView) to a grid.

When moving the box, the movement is locked to the grid and the box starts getting behind your finger if you drag diagonally or really fast.

So what is the best way to write a method that makes the box catch up and get back under the finger - it must move on the same path as your finger - and it must also not move through other boxes, so it needs collision detection - so I just can't do an Animate to new center point.

Any suggestions?

This is current code in use:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.superview];

    lastLocation = location;
}

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

    CGPoint offset = CGPointMake(self.center.x + location.x - lastLocation.x, self.center.y + location.y - lastLocation.y);
    CGPoint closestCenter = [self closestCenter:offset];
    CGRect rect = CGRectMake(offset.x - (self.size.width / 2), offset.y - (self.size.height / 2), self.size.width, self.size.height);

    if (fabsf(closestCenter.x - offset.x) < fabsf(closestCenter.y - offset.y)) {
        offset.x = closestCenter.x;
    }
    else {
        offset.y = closestCenter.y;
    }

    // Do collision detection - removed for clarity

    lastLocation = location;
    self.center = offset;
}
Это было полезно?

Решение

Don't use a relative offset movement. Instead, use the actual touch location as the desired position and then bound (modify) it based on the grid restrictions. In this way you won't get any lag behind the touch.

From your collision detection I guess there is a path that must be followed and a naive implementation will 'jump' the view to the touch across boundaries. A simple solution to this is to limit jumping to a maximum of half a grid square (so the user must bring the touch back to the view if they drop it).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top