我有 2 个视图并使用以下代码检测它们的碰撞。如果对象移动缓慢,即它给出了运动中的坐标,则工作正常。但是,当通过手势高速抛出视图时,中间坐标会被忽视。我只得到初始坐标和结束坐标。当 2 视图发生碰撞时,我希望它们尽可能靠近彼此。
func handlePan(_ pan: UIPanGestureRecognizer)
{
let view = pan.view
switch pan.state
{
case .began, .changed, .possible, .ended:
let point = pan.translation(in: view?.superview)
print(point)
let viewPoint = CGPoint(x: (view?.center.x)! + point.x, y: (view?.center.y)!+point.y)
prevCenterB = viewBlue.center
prevCenterR = viewRed.center
view?.center = viewPoint
if (viewRed.frame.intersects(viewBlue.frame))
{
print("Intersection")
let alert = UIAlertController(title: "Alert", message: "Collision of objects occured !!", preferredStyle: UIAlertControllerStyle.alert)
let actionOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
let actionCancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(actionOK)
alert.addAction(actionCancel)
self.present(alert, animated: true, completion: nil)
if view == viewRed
{
view?.center = prevCenterR!
}
else
{
view?.center = prevCenterB!
}
}
pan.setTranslation(.zero, in: view?.superview)
break
default:
break
}
}