0
votes

I'm new to Swift. I'm trying to figure out how to drag and drop and image onto a box and detect when the collision occurs. When I let gravity and animation act on the image it detects the collision. But when I drag the image to the box it doesn't detect it. I would appreciate any help! Thanks.

Here's the code I'm trying to use:

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)

    }
}
1
Try using , if CGRectIntersectsRect which returns true if 2 objects (their frames) intersectAbdullah Ossama Omari
Sprite kit would be better for such gamesAbdullah Ossama Omari
Abdulah: Thank you for that simple and elegant solution. The CGRectIntersectsRect works perfectly. I agree that Sprite kit would work better but I just needed a simple drag and drop, not a full on game. Thanks again for your help!Al Viera

1 Answers

0
votes

Use

if CGRectIntersectsRect(imageview.frame,imageview2.frame) {
//do something 
}

It returns true if two objects(their frames) intersect