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)
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