現在、スイフトの勉強をしております。
youtube等のコードを参考に、
画面に表示された四角を touchesBegan touchesMoved で任意の場所に動かし、
UIGravityBehaviorで重力を持つようにしました。
【改善した点】
touchesMovedで移動させた先で、四角が落下してしまうため、
タップ(クリック)している限りその場所に止まるようにし,
タップを離すと、落下するという動きが目標にしたいです。
追加すべきコードご教示いただけないでしょうか?
swift
1import UIKit 2 3class ViewController: UIViewController { 4 5 var location = CGPoint(x:0,y:0) 6 var animator: UIDynamicAnimator? 7 8 @IBOutlet weak var person: UILabel! 9 10 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 11 let touch: UITouch! = touches.first 12 location = touch.location(in: self.view) 13 person.center = location 14 } 15 16 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 17 let touch: UITouch! = touches.first 18 location = touch.location(in: self.view) 19 person.center = location 20 animator = UIDynamicAnimator(referenceView: self.view) 21 22 //add gravity 23 let gravity = UIGravityBehavior(items: [person]) 24 let direcction = CGVector(dx:0.0,dy:1.0) 25 gravity.gravityDirection = direcction 26 27 //collision 28 let boundries = UICollisionBehavior(items: [person]) 29 boundries.translatesReferenceBoundsIntoBoundary = true 30 31 //bounce 32 let bounce = UIDynamicItemBehavior(items: [person]) 33 bounce.elasticity = 0.5 34 35 animator?.addBehavior(bounce) 36 animator?.addBehavior(boundries) 37 animator?.addBehavior(gravity) 38 } 39 40 41 override func viewDidLoad() { 42 super.viewDidLoad() 43 44 //initialize the animator 45 animator = UIDynamicAnimator(referenceView: self.view) 46 47 //add gravity 48 let gravity = UIGravityBehavior(items: [person]) 49 let direcction = CGVector(dx:0.0,dy:1.0) 50 gravity.gravityDirection = direcction 51 52 //collision 53 let boundries = UICollisionBehavior(items: [person]) 54 boundries.translatesReferenceBoundsIntoBoundary = true 55 56 //bounce 57 let bounce = UIDynamicItemBehavior(items: [person]) 58 bounce.elasticity = 0.5 59 60 animator?.addBehavior(bounce) 61 animator?.addBehavior(boundries) 62 animator?.addBehavior(gravity) 63 person.center = CGPoint(x:160,y:330) 64 } 65 66 override func didReceiveMemoryWarning() { 67 super.didReceiveMemoryWarning() 68 // Dispose of any resources that can be recreated. 69 } 70 71 72} 73
回答でなくて申し訳ないのですが、touchesEndedで処理してあげたらどうでしょうか?
回答2件
あなたの回答
tips
プレビュー