Search code examples
swiftsprite-kitskphysicsbody

Stop a ball sprite kit with Swift


I need to know how to make a ball slow down after two or three seconds to apply an impulse

func setupPlayer(){
    player = SKSpriteNode(imageNamed: "ball")
    player.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    player.position = CGPoint(x: size.width/2, y: playableStart)
    let scale: CGFloat = 0.07
    player.xScale = scale
    player.yScale = scale
    player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)
    worlNode.addChild(player)
}

func movePlayer(){
    player.physicsBody?.applyImpulse((CGVectorMake( 50, 50)))
}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */
    for touch in (touches as! Set<UITouch>) {
        movePlayer()
    }
}

Solution

  • One way to decelerate a physics body is to reduce its velocity over time:

    override func update(currentTime: CFTimeInterval) {
        // This controls how fast/slow the body decelerates
        let slowBy:CGFloat = 0.95
        let dx = player.physicsBody!.velocity.dx
        let dy = player.physicsBody!.velocity.dy
        player.physicsBody?.velocity = CGVectorMake(dx * slowBy, dy * slowBy)
    }