[英]Is it possible to simulate gravity to an object / UIView in UIDynamicKit?
[英]Moving an object (UIView) in Swift with gravity/collision/elasticity already setup
我想快速創建一個從屏幕頂部開始並落到屏幕底部並停留在那里的正方形。 我還希望能夠用我的手指將它拖向頂部並使其再次落向屏幕底部。 關於如何做到這一點的任何提示?
我已經能夠創建一個落在屏幕底部的正方形。 我也可以用手指移動它。 但問題是,每當我移動它時,方塊就停留在同一個地方。 我移動它后,重力/碰撞/彈性似乎不起作用。 我希望我的手指離開方塊后它會掉下來。 請參閱下面的我的代碼的摘錄。 可能有一些簡單的東西我想念。 任何提示將不勝感激。
import UIKit
class ViewController: UIViewController {
var greenSquare: UIView?
var redSquare:UIView?
var animator: UIDynamicAnimator?
override func viewDidLoad() {
super.viewDidLoad()
createFallingObject()
func createFallingObject() {
//remove square from superview
redSquare?.removeFromSuperview()
//create the shape
var dimen = CGRect(x: 130,y: 25,width: 90,height: 90)
redSquare = UIView(frame: dimen)
redSquare?.backgroundColor = UIColor.red
//then add to the screen
self.view.addSubview(redSquare!)
//Initialize the animator
animator = UIDynamicAnimator(referenceView: self.view)
//Add gravity to the squares
let gravity = UIGravityBehavior(items: [redSquare!])
let direction = CGVector(dx: 0.0, dy: 0.05)
gravity.gravityDirection = direction
//Collision
let boundaries = UICollisionBehavior(items: [redSquare!])
boundaries.translatesReferenceBoundsIntoBoundary = true
//Elasticity
let bounce = UIDynamicItemBehavior(items: [redSquare!])
bounce.elasticity = 0.3
// 1. create a gesture recognizer (tap gesture)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
//add pan gesture Regcognizer to the red square
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
redSquare?.addGestureRecognizer(panGestureRecognizer)
animator?.addBehavior(boundaries)
animator?.addBehavior(bounce)
animator?.addBehavior(gravity)
}
//this method handle pan
func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
let translation = gestureRecognizer.translation(in: self.view)
// note: 'view' is optional and need to be unwrapped
gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y + translation.y)
gestureRecognizer.setTranslation(CGPoint.zero, in: self.view)
//redSquare?.frame.origin.x = translation.x
//redSquare?.frame.origin.y = translation.y
}
}
// 3. this method is called when a tap is recognized
func handleTap(sender: UITapGestureRecognizer) {
createFallingObject()
}
}
您應該在平移手勢開始時從UIDynamicAnimator
刪除該項目,並在它結束時將其添加回來。
當一個視圖被添加到動態動畫師時,它的位置應該由動畫師和動畫師單獨確定。 從動畫師中刪除項目將允許視圖使用其框架正常定位。 將它添加回動畫師將導致動畫師從當前狀態恢復定位。
或者,如果您需要手動更新項目的位置(即不基於動畫師的物理特性),您應該調用animator.updateItem(usingCurrentState: myDynamicItem)
,其中myDynamicItem
是您要更新的項目。
謝謝貝優武夫。 animator?.removeAllBehavior() 在平移手勢例程中發揮了作用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.