GS. GS. - 6 months ago 43
Swift Question

Spritekit Changing Gravity

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.


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.physicsBody?.isDynamic = true
spaceship.physicsBody = SKPhysicsBody(circleOfRadius: spaceship.size.width / 2);


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download