【问题标题】:touchesMoved, how do I make my view catch up - and stay under the finger?touchesMoved,我如何让我的观点赶上 - 并保持在手指之下?
【发布时间】:2014-01-03 15:23:31
【问题描述】:

我编写了一些代码,将框 (UIView) 移动到网格中。

移动框时,移动被锁定在网格中,如果您沿对角线拖动或非常快地拖动,框就会开始移到您的手指后面。

那么,编写一个使盒子赶上并回到手指下的方法的最佳方法是什么——它必须与你的手指在同一条路径上移动——而且它也不能穿过其他盒子,所以它需要碰撞检测 - 所以我不能对新的中心点进行动画处理。

有什么建议吗?

这是当前使用的代码:

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

【问题讨论】:

  • 专业提示:您不需要 lastLocation 变量。 UIView 上有一个 previousLocationInView: 方法。

标签: ios objective-c cocoa-touch collision-detection multi-touch


【解决方案1】:

不要使用相对偏移运动。相反,使用实际触摸位置作为所需位置,然后根据网格限制对其进行绑定(修改)。这样您就不会在触摸后出现任何滞后。

从您的碰撞检测中,我猜有一条必须遵循的路径,并且天真的实现会将视图“跳转”到跨越边界的触摸。一个简单的解决方案是将跳跃限制在最多半个方格内(因此,如果用户放下触摸,则必须将触摸带回视图)。

【讨论】:

  • 如果我使用实际的触摸位置,我会在对角线穿过网格角时得到一个跳跃的框。当前碰撞检测只是检测当前框是否移动到网格框架之外以及是否与其他框相交。
猜你喜欢
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多