Ignatius_Gim Ignatius_Gim - 3 months ago 22
Swift Question

Jumping with Sprite Kit and Swift

I am creating an app in Sprite Kit and Swift and want to create a sprite that jumps upwards while the screen is pressed, therefore jumping higher as the screen is pressed higher. I have achieved that effect, but gravity in the physics engine is not being applied until after the screen is released. Therefore the jumps are infinite (increasing exponentially) rather than levelling off at a certain point (like a quadratic equation / parabola).

How does one apply gravity actively during the motion of a sprite?

Here is my basic movement code:

override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
// touched is true while screen is touched
if touched {
nodeLeft.physicsBody?.applyImpulse(CGVector(dx: -5, dy: 0))

NOTE: The object is jumping right and left rather than up and down


The gravity should be working constantly, and probably is. As you apply an impulse on every tick however, this force is much stronger than the gravity.

What you need to do is to decrease the effect of the impulse over time. This can be achieved in a number of ways, for instance by using the position of the sprite as a base for the impulse: The higher the sprite position, the lower the impulse.

if touched {
    let minX: CGFloat = 200 // some suitable value
    let multiplier: CGFloat = 10
    let force = max(0, (nodeLeft.position.x / minX - 1) * multiplier)
    nodeLeft.physicsBody?.applyImpulse(CGVector(dx: -force, dy: 0))

The minX value in the above example probably makes no sense. But the logic is fairly sound I believe. You obviously need to experiment and tweak this (and the multiplier) to suit your needs.