【发布时间】: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)
}
}
【问题讨论】:
-
附注这段代码没有错误。它工作正常。只需要知道如何检测碰撞