簡體   English   中英

使用UICollisionBehavior調整UIView的大小

[英]Resize UIView with UICollisionBehavior

我最近正在嘗試使用UIKitDynamics創建一個類似pong的游戲。 我成功構建了核心游戲。 現在,我想添加一些其他機制。

例如,減少槳葉尺寸的行為。 我添加了一個執行此類操作的NSTimer。 但是我注意到,槳的CollisionBehavior不會與槳同時調整大小。

這是我的代碼:

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

}

有沒有人意識到這一點?

非常感謝你!

首先向划槳添加邊界。 就像是:

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

然后使用func crashBehavior檢查沖突並執行轉換。 就像是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM