Search code examples
swiftsprite-kittextfieldsksceneuitextfielddelegate

How to reload scene after changing its physics world gravity based on user input?


I want to allow the user to change gravity based on their input in gravity text field and pass the input from view controller to a SKScene (PhysicsScene) but I don't know how to reload scene so that it would use the custom gravity by the user instead of its default value.

view of simulator

class SimulationViewController: UIViewController, UITextFieldDelegate {

    var sceneNode : PhysicsScene?

    @IBOutlet weak var heightTextField: UITextField!
    @IBOutlet weak var massTextField: UITextField!
    @IBOutlet weak var gravityTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        sceneNode = PhysicsScene(size: view.frame.size)
        gravityTextField.delegate = self
        if let view = self.view as! SKView? {
            view.presentScene(sceneNode)
            view.ignoresSiblingOrder = true
            view.showsPhysics = true
        }
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.tag == 0 {
            if let text = textField.text {
                sceneNode?.customGravity = Double(text)!
                print(text)
            }
        }
        return true
    }

Please help! Thank you!


Solution

  • You have 2 options, make a property in your PhysicsScene class

      var customGravity : Double = 0{ didSet { physicsWorld.gravity = {CGPoint(x:0 y:CGFloat(customGravity)}}
    

    or drop custom gravity and set it directly

     func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            if textField.tag == 0 {
                if let text = textField.text {
                    sceneNode?.customGravity = physicsWorld.gravity = {CGPoint(x:0 y:CGFloat(Double(text)!)}
                    print(text)
                }
            }
            return true
        }
    

    I do not have XCode available to check my typos, you may have to unwrap some variables