Search code examples
swiftanimationcgrect

UIView.animate and CGRect don't work - Swift 4


I'm making this app where when you press a button , the character goes up and after that it's gonna go down.(I want it to act like this : When it's pressed , it has to go up 200y , then it starts going down) This is my code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var TheCharacter: UIImageView!
    @IBOutlet weak var TheRocket: UIImageView!

    @IBAction func TheCharacterJumps(_ sender: Any) {

        let TheCharacterY = self.TheCharacter.frame.origin.y
        UIView.animate(withDuration: 0.35, animations: {
            self.TheCharacter.frame = CGRect(x: 167, y: TheCharacterY - 194, width: 40, height: 40)
        }) { (finished) in

        }
        UIView.animate(withDuration: 2, animations: {
            self.TheCharacter.frame = CGRect(x: 167, y: TheCharacterY + 435, width: 40, height: 40)
        }) { (finished) in

        }
    }
}

So it's like this : When the button is pressed , the character goes up and then it starts to fall. But when the button is pressed two or more times in a row , instead of going up for like 200y , it goes up for only like 50y. How can I prevent that from happening?


Solution

  • If you want a "flappy" animation you should use dynamic animators and add gravity to the scene and force to elements. Then UIKit will calculate animations.

    Apple doc is: UIDynamicAnimator.

    In this case, every time you press button/screen add some upward force to the view and it will go up at its own and start going down after losing speed.

    Look at Ray Wenderlich tutorial: click