Search code examples
swiftskspritenodetouchesmoved

How to move an SKSpriteNode along a horizontal line


I have an SKSpriteNode that can be moved anywhere I am touching, and I want it to move where my finger is, just along a horizontal line so that is cannot move vertically.

class GameScene: SKScene {

var ship = SKSpriteNode()

override func didMoveToView(view: SKView) {
    /* Setup your scene here */



    let shipTexture = SKTexture(imageNamed: "Evaders Art/EvadersShipVert2.png")

    ship = SKSpriteNode(texture: shipTexture)

    ship.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame) - 250)

    ship.size = CGSize(width: 90, height: 115)

    shipTexture.filteringMode = SKTextureFilteringMode.Nearest

    ship.zPosition = 2





    self.addChild(ship)



}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    var nodeTouched = SKNode()
    var currentNodeTouched = SKNode()

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        nodeTouched = self.nodeAtPoint(location)
        ship.position = location

    }

}

Here's my code, thanks in advance.


Solution

  • Try this:

    ship.position.x = location.x
    

    Currently, you are setting the ship's location to the location of the tap. If you want a consistent y position, only set the x.