2015-12-07 53 views
1

我最近试图用UIKitDynamics创建一个类似pong的游戏。我成功地构建了核心游戏。现在我想添加一些额外的机制。用UICollisionBehavior调整UIView的大小

例如,一种行为,即减少桨的大小。我添加了一个NSTimer来执行此类操作。但我注意到桨的碰撞行为不会与桨同时调整大小。

这里是我的代码:

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) 

} 

这里是桨控制功能:

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) 
    } 

} 

大家有一个想法,认识到?

非常感谢!

回答

0

首先向桨叶添加边界。例如:

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

然后使用func collisionBehavior来检查碰撞并执行转换。例如:

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) 
    } 
}