Mike Rosinsky
Mike Rosinsky

Reputation: 21

UIKit Collision Detection and actions

I am developing an iOS app with swift and i ran into a problem. Using solely UIKit, I have a square that falls onto a platform, bounces back to its original position, and keeps going. I want the platform to change color every time the square hits it but i don't know how to detect that the square has come into contact with the platform. Please help. Here is the the code

import UIKit
import SpriteKit




class PlayScreen : UIViewController {

    @IBOutlet var ScreenBack: UIImageView!
    @IBOutlet var Platform: UIImageView!

    var squareView: UIImageView!
    var gravity: UIGravityBehavior!
    var animator: UIDynamicAnimator!
    var collision: UICollisionBehavior!
    var itemBehaviour: UIDynamicItemBehavior!

    override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    // Creating a bouncing Ball with the barrier of the platform
    squareView = UIImageView(frame: CGRect(x: ScreenBack.frame.width/2, y: ScreenBack.frame.height/4, width: 40, height: 40))
    squareView.frame.origin.x-=squareView.frame.width/2
    squareView.image = redBall
    view.addSubview(squareView)

    animator = UIDynamicAnimator(referenceView: view)
    gravity = UIGravityBehavior(items: [squareView])
    animator.addBehavior(gravity)

    collision = UICollisionBehavior(items: [squareView])
    collision.translatesReferenceBoundsIntoBoundary = true
    collision.addBoundaryWithIdentifier("barrier", fromPoint: CGPointMake(self.Platform.frame.origin.x, self.Platform.frame.origin.y), toPoint: CGPointMake(self.Platform.frame.origin.x + self.Platform.frame.width, Platform.frame.origin.y))
    animator.addBehavior(collision)


    itemBehaviour = UIDynamicItemBehavior(items: [squareView])
    itemBehaviour.elasticity = 1.0
    itemBehaviour.resistance = 0.0
    animator.addBehavior(itemBehaviour)

    }
}

Upvotes: 0

Views: 1129

Answers (1)

user4955320
user4955320

Reputation: 41

to detect collision use UICollisionBehaviorDelegate

class ViewController: UIViewController, UICollisionBehaviorDelegate {

Set your collision behavior object delegate to self

collision.collisionDelegate=self

Add add the following function

func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying, atPoint p: CGPoint) {
     println("Contact - \(identifier)")
}

Upvotes: 4

Related Questions