我创建了一个UIimageView的子类,因为我想多次使用这个imageview。我使用touchesmoved来拖动图像。因此,当我使用同一类的多个图像时,我想知道它们是否相互交叉。这是图像类代码
import UIKit
class imgBall: UIImageView {
private var xOffset: CGFloat = 0.0
private var yOffset: CGFloat = 0.0
required init(coder aDecoder:NSCoder) {
fatalError("use init(point:")
}
init(point:CGPoint) {
let image = UIImage(named: "ball.png")!
super.init(image:image)
self.frame = CGRect(origin: point, size: CGSize(width: 100, height: 100))
self.userInteractionEnabled = true
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let point = touches.anyObject()!.locationInView(self.superview)
xOffset = point.x - self.center.x
yOffset = point.y - self.center.y
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
let point = touches.anyObject()!.locationInView(self.superview)
self.center.x = point.x - xOffset
}
}
这就是我在gameviewcontroller中使用它的方式
viewDidLoad() {
var ball1 = imgBall(point: CGPoint(x: 20, y: 0))
self.view.addSubview(ball1)
var ball2 = imgBall(point: CGPoint(x: 50, y: 70))
self.view.addSubview(ball2)
}
那么我怎么知道它们是否相互交叉/碰撞?
答案 0 :(得分:0)
你必须使用 CGRectIntersectsRect :
if (CGRectIntersectsRect(ball1.frame,ball2.frame) {
// they intersect
} else {
// they're safe
}