swift - UIKit 碰撞检测和 Action

标签 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)

    }
}

最佳答案

使用 UICollisionBehaviorDelegate 检测碰撞

class ViewController: UIViewController, UICollisionBehaviorDelegate {

将你的碰撞行为对象委托(delegate)给自己

collision.collisionDelegate=self

添加添加如下函数

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

关于swift - UIKit 碰撞检测和 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29360060/

相关文章:

ios - 为什么我们必须在调用 addChild(UIViewController) 之后调用 func didMove(toParent Parent : UIViewController? ) ?

java - 我正在使用 .hashCode() 创建哈希值。 Java 中是否有一个库可以执行双重哈希来解决冲突?

ios - 如何在回归测试中模拟 UITouches?

objective-c - 适用于 iOS 的沙子物理学

Javascript Canvas : Collision against enemies not entirely working when rotating player

iphone - 将返回键更改为 'Continue'

ios - SwiftUI 中水平居中 View

ios - 在另一个函数中快速包装函数

ios - UIWebView 中 PDF 周围的黑色边框,如何使用 Swift 删除

iphone - UIViewController 中 subview 的布局和大小