2
votes

I've been trying to be able to alter gravity by using

override func touchesBegan(_ touches: Set<UITouch>, with event: 
UIEvent?) {
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
}

but that doesn't seem to change the gravity at all. When I use the same code in the didMove function, it works.

EDIT 1:

Here's the code for for my SKSpriteNode:

spaceship = SKSpriteNode(imageNamed: "Spaceship")

    spaceship.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
    spaceship.setScale(0.1)
    spaceship.physicsBody?.isDynamic = true
    spaceship.physicsBody = SKPhysicsBody(circleOfRadius: spaceship.size.width / 2);


    addChild(spaceship)
1
Could you please be more specific about how you can find out that the gravity doesn't change ? In there any other elements in your SKScene that you are expecting to move/fall? If yes, did you set their physics bodies' mass/affectedByGravity properties?user8606263
Are you expecting the sprite to stop immediately after turning off gravity?0x141E
Like @0x141E pointed out, you would need to change the velocity/speed property of your spaceship if you want it to stop right away and then go in an other direction, otherwise forces will still be applied on it.user8606263
Remember, gravity is a force. It causes acceleration. If you turn off gravity, you're not turning off motion, you're just turning off acceleration. If a body is moving when you turn off gravity, it will continue moving until some other force acts on it. Also, the line spaceship.physicsBody?.isDynamic = true in your code is doing nothing.SaganRitual
That makes sense. I used spaceship.physicsBody?.velocity = CGVector(dx: 0, dy: 0) to stop it.GS.

1 Answers

1
votes

It works in didMove because the objects will have no forces applied to them, thus they are still

When you change the gravity mid-game, the objects are still in motion from the previous gravity--changing the gravity only affect /future/ forces applied to the objects.

You need to both change the gravity, AND the velocity of the nodes you want affected in your touch function to get the desired effect.

Also, for brevity, you can directly access the dy value without having to assign a new CGVector to it--this helps performance some as well.

spaceship.physicsBody!.velocity.dy = 0