1 Reply
      Latest reply on Jul 28, 2019 3:52 AM by Claude31
      Garian Level 1 Level 1 (0 points)

        I want to implement a ball that is bounding continuously.

        If you execute the following code, the ball bounces to a position higher or lower than the position where it started dropping.

        Is this an error from the calculation? Or is the implementation wrong?

         

        class ViewController: UIViewController {
        
            @IBOutlet weak var imageView: UIImageView!
            var dynamicAnimator: UIDynamicAnimator!
            override func viewDidLoad() {
                super.viewDidLoad()
            }
        
            @IBAction func fallButtonTapped(_ sender: Any) {
                let gravityBehavior = UIGravityBehavior(items: [imageView])
                dynamicAnimator = UIDynamicAnimator(referenceView:  self.view)
                dynamicAnimator.addBehavior(gravityBehavior)
                
                let collisionBehavior = UICollisionBehavior(items: [imageView])
                collisionBehavior.translatesReferenceBoundsIntoBoundary = true
                dynamicAnimator.addBehavior(collisionBehavior)
                
                let dynamicItemBehavior = UIDynamicItemBehavior(items: [imageView])
                dynamicItemBehavior.elasticity = 1.0
                dynamicItemBehavior.resistance = 0.0
                dynamicItemBehavior.friction = 0.0
                dynamicAnimator.addBehavior(dynamicItemBehavior)
            }
            
        }
        
        • Re: The error of bounding ball using UIDynamicAnimator
          Claude31 Level 8 Level 8 (8,525 points)

          I tested (in iPhone XR simulator - 12;2) and it works perfectly: it bounces up exactly to the starting point, indefinetely.

           

          But tested on iPhone 5s simulator, here I observe the problem, bouncing more and more higher than original position.

          Same problem with iPhone 8s simulator. Or with iPhone Xs

           

          Did you test on real device or on simulator ?

           

          I wonder if setting setTranslatesReferenceBoundsIntoBoundary is necessary

          See discussion here:

          https://stackoverflow.com/questions/48249288/uicollisionbehaviordelegate-methods-not-called

           

          Made a quick test adding

              collisionBehavior.setTranslatesReferenceBoundsIntoBoundary(with: UIEdgeInsets(top: 20, left: 20, bottom: 200, right: 20))

           

          Does not solve the problem.

           

          Tested on iPad simulators:

          same problem with iPadPro (3rd generation).

          But works OK on iPad (5th generation)