Search code examples
iosswiftsprite-kitgame-physics

Swift SpriteKit Gravity Point


I need to make something like a Gravity Point in Swift. The SpriteNode is in the middle of the screen, and by Left or Right Gestures it can move along the x-axis.

But after for e.g. a 'RightSwipe', it should come back to his starting point. You could say it should look like a jump along the x-axis.

The World Gravity cant be a specific point, so how can I 'Force' it to come back to his original point?

I tried it with SKFieldNode's RadialGravityField, but after the Nodes impulse is made, it goes back to his original point and disappears. How can I avoid that?

My Code:

{ 
.......

Node = SKSpriteNode(texture: Node1)
Node.size = CGSize(width: 100, height: 140)
Node.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 4)
Node.zPosition = 3
Node.runAction(RunAnimation)

Node.physicsBody = SKPhysicsBody(rectangleOfSize: Node.size)
Node.physicsBody?.dynamic = true
Node.physicsBody?.allowsRotation = false
Node.physicsBody?.usesPreciseCollisionDetection = true
Node.physicsBody?.restitution = 0
Node.physicsBody?.velocity = CGVectorMake(0, 0)

self.addChild(Node)

let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("SwipeRight:"))
swipeRight.direction = .Right
view.addGestureRecognizer(swipeRight)


let swipeLeft:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("SwipeLeft:"))
swipeLeft.direction = .Left
view.addGestureRecognizer(swipeLeft)

}

func SwipeRight(recognizer:UISwipeGestureRecognizer) {

Node.physicsBody?.applyImpulse(CGVectorMake(10,0))

}

func SwipeLeft(recognizer:UISwipeGestureRecognizer) {

Node.physicsBody?.applyImpulse(CGVectorMake(-10,0))

}

override func update(currentTime: CFTimeInterval) {

if(Node.position.x > self.frame.size.width / 1.6)
    {
        fieldNode = SKFieldNode.radialGravityField()
        fieldNode.enabled = true
        fieldNode.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 4)
        fieldNode.strength = 0.4
        addChild(fieldNode)
    }

    if(Node.position.x < self.frame.size.width / 2.6)
    {
        fieldNode = SKFieldNode.radialGravityField()
        fieldNode.enabled = true
        fieldNode.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 4)
        fieldNode.strength = 0.4
        addChild(fieldNode)
    }

Solution

  • Sounds like a job for a radial gravity SKFieldNode. link