【发布时间】: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