0
我是新來的Swift。我試圖弄清楚如何拖放和圖像到盒子上並檢測碰撞發生的時間。當我讓重力和動畫在圖像上作用時,它會檢測到碰撞。但是,當我將圖像拖到框中時,它不會檢測到它。我將不勝感激任何幫助!謝謝。迅速拖放與碰撞
這裏是我想要使用的代碼:
import UIKit
import AVFoundation
class Punc2ViewController: UIViewController, UICollisionBehaviorDelegate {
var player2:AVAudioPlayer = AVAudioPlayer()
var error : NSError? = nil
var location = CGPoint(x: 0, y: 0)
var animator: UIDynamicAnimator!
var gravity: UIGravityBehavior!
var collision: UICollisionBehavior!
@IBOutlet weak var period: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
period.center = CGPointMake(650, 100)
view.addSubview(period)
let barrier = UIView(frame: CGRect(x: 600, y: 200, width: 130, height: 20))
barrier.backgroundColor = UIColor.redColor()
view.addSubview(barrier)
animator = UIDynamicAnimator(referenceView: view)
//gravity = UIGravityBehavior(items: [period])
//animator.addBehavior(gravity)
collision = UICollisionBehavior(items: [period])
collision.collisionDelegate = self
// add a boundary that has the same frame as the barrier
collision.addBoundaryWithIdentifier("barrier", forPath: UIBezierPath(rect: barrier.frame))
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
collision.action = {
}
}
func collisionBehavior(behavior: UICollisionBehavior!, beganContactForItem item: UIDynamicItem!, withBoundaryIdentifier identifier: NSCopying!, atPoint p: CGPoint) {
println("Boundary contact occurred - \(identifier)")
}
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translationInView(self.view)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPointZero, inView: self.view)
}
}
嘗試使用,如果CGRectIntersectsRect返回如果2個對象(它們的幀)相交,則爲true –
Sprite套件對於此類遊戲會更好 –
Abdulah:感謝您提供這種簡單優雅的解決方案。 CGRectIntersectsRect完美地工作。我同意Sprite套件可以更好地工作,但我只需要簡單的拖放操作,而不是完整的遊戲。再次感謝你的幫助! –