简体   繁体   中英

UICollisions in Swift

I'm required to make a Breakout app in a Single-View Application in the Swift language. However, I'm having trouble getting the "ball" to respond to hitting the barrier. Additionally, I'm having trouble getting the barrier to disappear after it is hit. Does anyone have the solution to this, or does anyone have an example app I can look off of? This is in Single View Application, not 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)    
}

You need to have both the objects in your UICollisionBehavior if you want them to collide. Depending on what you need there is several possibilities. I suppose that you need your ball to bounce on barrier, so create the behavior:

let collisionBehavior = UICollisionBehavior(blueSquare: array)

and then add a rigid boundary that correspond to your barrier:

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];

Now if you want to capture the collision you need to add a delegate to collisionDelegate . This delegate should be able to respond to several methods when a hit occurs, (read documentation about UICollisionBehaviorDelegate .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM