DAY 25
0
Software Development

## 當頭碰到身體後的動畫運作

``````//把蛇陣列裡面的每個點都賦予引力和碰撞，再加上重力加速度，所有的物體自然會往下掉
for i in 1..<snakePoint.count{
if self.snakePoint[0].center == tempPoint[i]{
ani = UIDynamicAnimator(referenceView: mainView.secondView)
let gravity = UIGravityBehavior(items: snakePoint)      //引力
let collision = UICollisionBehavior(items: snakePoint)  //碰撞
collision.translatesReferenceBoundsIntoBoundary = true  //在邊界停止
gravity.gravityDirection = CGVector (dx: 0.0, dy: 1.0)  //重力加速度的方向
let itemBehavior = UIDynamicItemBehavior(items: snakePoint)
itemBehavior.angularResistance = 0      //碰到牆旋轉速
itemBehavior.elasticity = 1.0       //反彈力
timer?.invalidate()
viewSlideUp()
}
}
``````

## 滑出的一個結束遊戲與重新遊戲的視窗

``````override func viewWillAppear(_ animated: Bool) {
let height = appearView.frame.height
//以下三行為設定view的約束
appearView.heightAnchor.constraint(equalToConstant: height).isActive = true
appearView.trailingAnchor.constraint(equalTo: mainView.trailingAnchor, constant: -10).isActive = true
//把底部的約束當作一個id來用，用來當作判斷是否有呼叫到此id，有的話就讓底部的約束改變這時就會進入ViewSlideUp的方法裡
let hide = appearView.bottomAnchor.constraint(equalTo: mainView.bottomAnchor, constant: height)
hide.identifier = "hide"
hide.isActive = true
appearView.backgroundColor = UIColor(displayP3Red: 0, green: 0, blue: 0, alpha: 0)
super.viewWillAppear(animated)
}
``````

``````func viewSlideUp(){
for i in mainView.constraints{
if i.identifier == "hide"{
let showHeight = (mainView.frame.height - appearView.frame.height)/2
i.constant = -showHeight
break
}
}
UIView.animate(withDuration: 1.25) {
self.mainView.layoutIfNeeded()
}
}
``````

``````func tapViewBtn(){
for i in mainView.constraints{
if i.identifier == "hide"{
let showHeight = (mainView.frame.height - appearView.frame.height)/2
i.constant = showHeight
break
}
}
UIView.animate(withDuration: 1.0) {
self.mainView.layoutIfNeeded()
}
}
``````

iOS APP開發學習筆記 30