UIKit碰撞检测和动作

时间:2015-03-31 03:22:52

标签: swift uikit collision

我正在开发一个带有swift的iOS应用程序,但我遇到了一个问题。仅使用UIKit,我有一个落在平台上的正方形,弹回到原来的位置,并继续前进。我希望平台每次正方形都能改变颜色,但我不知道如何检测到正方形已经与平台接触。请帮忙。这是代码

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)

    }
}

1 个答案:

答案 0 :(得分:4)

检测碰撞使用UICollisionBehaviorDelegate

class ViewController: UIViewController, UICollisionBehaviorDelegate {

将碰撞行为对象委托设置为自我

collision.collisionDelegate=self

添加添加以下功能

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