2

我需要在 Swift 语言的单视图应用程序中制作一个 Breakout 应用程序。但是,我无法让“球”对击中障碍做出反应。此外,我无法让障碍物在被击中后消失。有没有人对此有解决方案,或者有没有人有我可以查看的示例应用程序?这是在单视图应用程序中,而不是 Sprite。

var dynamicAnimatior = UIDynamicAnimator()

override func viewDidLoad() {
    super.viewDidLoad()
    dynamicAnimatior = UIDynamicAnimator(referenceView: view)
    setupViews()
}

func setupViews() {

    let blueSquare = UIView(frame: CGRectMake(100, 100, 50, 50))
    blueSquare.backgroundColor = UIColor.blueColor()
    view.addSubview(blueSquare)

    let barrier = UIView(frame: CGRect(x: 0, y: 300, width: 130, height: 20))
    barrier.backgroundColor = UIColor.redColor()
    view.addSubview(barrier)

    addDynamicBehaviors([blueSquare])
}

func addDynamicBehaviors(array: [UIView]) {

    let dynamicItemBehavior = UIDynamicItemBehavior(items: array)
    dynamicItemBehavior.density = 1.0
    dynamicItemBehavior.friction = 0.0
    dynamicItemBehavior.resistance = 0.0
    dynamicItemBehavior.elasticity = 1.0
    dynamicAnimatior.addBehavior(dynamicItemBehavior)

    let pushBehavior = UIPushBehavior(items: array, mode: .Instantaneous)
    pushBehavior.magnitude = 1.0
    pushBehavior.pushDirection = CGVectorMake(0.5, 0.5)
    dynamicAnimatior.addBehavior(pushBehavior)

    let collisionBehavior = UICollisionBehavior(items: array)
    collisionBehavior.translatesReferenceBoundsIntoBoundary = true
    collisionBehavior.collisionMode = .Everything
    collisionBehavior.collisionDelegate = self

    dynamicAnimatior.addBehavior(collisionBehavior)    
}
4

1 回答 1

0

UICollisionBehavior如果你想让它们发生碰撞,你需要同时拥有这两个对象。根据您的需要,有几种可能性。我想你需要你的球在障碍物上反弹,所以创建行为:

let collisionBehavior = UICollisionBehavior(blueSquare: array)

然后添加与您的障碍相对应的刚性边界:

let edge = CGPointMake(barrier.frame.origin.x + barrier.frame.size.width,
                       barrier.frame.origin.y + barrier.frame.size.heigth);
collisionBehavior.addBoundaryWithIdentifier("barrier",
                                            fromPoint:barrier.frame.origin,
                                            toPoint:rightEdge];

现在,如果要捕获碰撞,则需要将委托添加到collisionDelegate. 当发生命中时,这个委托应该能够响应几种方法,(阅读有关UICollisionBehaviorDelegate的文档。

于 2016-05-26T15:57:04.337 回答