2015-12-07 87 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) 
    } 
}