Search code examples
swiftxcodesprite-kitskspritenode

In Xcode how would I get a SkSpriteNode to move up when clicked on?


How do I get the SkSpriteNode to move up when clicked? -Thanks

https://i.sstatic.net/fcOvr.png


Solution

  • lets say your node is called box

    use the touches began function

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for _ in touches{
            let touch:UITouch = touches.first!
            let touchLocation = touch.location(in: self)
            box.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
            box.physicsBody?.applyImpulse(CGVector(dx: 0, dy:300))
    
        }
    
    }
    

    the applyImpusle method takes an x value to move along the x axis(left or right) and takes a y value to move along the y axis (up or down). set dy accordingly.

    rest of it depends on your scene properties like gravity , friction , mass of the box and so on