Search code examples
sprite-kitswift3skspritenodeuitouchuievent

Apply impulse to a SKSpriteNode from a user swipe


Can anyone tell me why when I try to apply an impulse to a node like this it disappears?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch:UITouch = touches.first! as UITouch
    startPoint = touch.location(in: view)
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    defer {
        startPoint = nil
    }
    guard touches.count == 1, let startPoint = startPoint else {
        return
    }
    if let touch = touches.first {
        let endPoint = touch.location(in: view)
        //Calculate your vector from the delta and what not here
        direction = CGVector(dx: endPoint.x - startPoint.x, dy: endPoint.y - startPoint.y)

        L1Ball.physicsBody?.applyImpulse(CGVector(dx: direction.dx.hashValue, dy: direction.dy.hashValue))
        }
}

I think it has something to do with the way I am using hashValue. I don't know another way to get the values from the CGVector direction. If I try to use direction itself as the impulse vector it just crashes. Any insight? Thanks!


Solution

  • Your code worked for me when I removed the .hashValue from direction.dx and direction.dy (hash values are used for comparisons). Oh and your ball node isn't disappearing. Those hash values are large enough that when you apply them on a ball as a force, the speed of the ball is big enough that by the time the next frame is rendered the ball is off the screen.