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