【问题标题】:UIKit Collision Detection and actionsUIKit 碰撞检测和动作
【发布时间】:2015-03-31 03:22:51
【问题描述】:

我正在使用 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)

    }
}

【问题讨论】:

  • 附注这段代码没有错误。它工作正常。只需要知道如何检测碰撞

标签: swift uikit collision


【解决方案1】:

使用 UICollisionBehaviorDelegate 检测碰撞

class ViewController: UIViewController, UICollisionBehaviorDelegate {

将您的碰撞行为对象委托设置为 self

collision.collisionDelegate=self

添加添加如下功能

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

【讨论】:

    猜你喜欢
    • 2011-09-05
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多