[英]touchesMoved, how do I make my view catch up - and stay under the finger?
I have written some code that restricts the movement of a box (UIView) to a grid. 我写了一些代码,将框(UIView)的移动限制为网格。
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.