1

I'm recently trying to create a little pong-like game with UIKitDynamics. I succeeded in building up the core game. Now I want to add some additional mechanics.

For example a behaviour, that decrease the size of the paddle. I have added a NSTimer that do this kind action. But I noticed that the CollisionBehavior of the paddle don't resize at the same time with the paddle.

Here is my code:

func decreaseBarSize() {

    player1Bar.bounds = CGRect(x: player1Bar.frame.minX, y: player1Bar.frame.minY, width: player1Bar.bounds.width - 1, height: player1Bar.frame.height)
    player1Bar.layoutIfNeeded()
    animator.updateItemUsingCurrentState(player1Bar)

}

And here is the function of the paddle-controls:

func moveBar() {

    if player == .Player1 {

        let barFrame = player1Bar.frame

        switch self.direction {
        case .Right:
            if Int(barFrame.maxX) < superviewWidth - 10 {
                player1Bar.frame = CGRect(x: barFrame.minX + 1, y: barFrame.minY, width: barFrame.width, height: barFrame.height)
            }
            break
        case .Left:
            if Int(barFrame.minX) > 10 {
                player1Bar.frame = CGRect(x: player1Bar.frame.minX - 1, y: barFrame.minY, width: barFrame.width, height: barFrame.height)
            }
            break
        default:
            break
        }
        animator.updateItemUsingCurrentState(player1Bar)
    } else if player == .Player2 {

        let barFrame = player2Bar.frame

        switch self.direction {
        case .Right:
            if Int(barFrame.maxX) < superviewWidth - 10 {
                player2Bar.frame = CGRect(x: barFrame.minX + 1, y: barFrame.minY, width: barFrame.width, height: barFrame.height)
            }
            break
        case .Left:
            if Int(barFrame.minX) > 10 {
                player2Bar.frame = CGRect(x: barFrame.minX - 1, y: barFrame.minY, width: barFrame.width, height: barFrame.height)
            }
            break
        default:
            break
        }
        animator.updateItemUsingCurrentState(player2Bar)
    }

}

Has anybody an idea to realise that?

Thank You very much!

Tom Kuschka
  • 463
  • 1
  • 8
  • 17

1 Answers1

0

First add a boundary to the paddle. Something like:

yourBehavior.collider.addBoundaryWithIdentifier("aBarrierName", forPath: UIBezierPath(rect: yourPlayerPaddle.frame))

Then use func collisionBehavior to check for collisions and perform transform. Something like:

func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, atPoint p: CGPoint) {

    print("Contact by - \(identifier)")
    let collidingView = item as? UIView
    collidingView?.transform = CGAffineTransformMakeScale(1.5 , 1)

    UIView.animateWithDuration(0.4) {
        collidingView?.transform = CGAffineTransformMakeScale(1 , 1)
    }
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Etihv
  • 43
  • 4