How do I use touch to only move my object in the y-coordinate?

659 Views Asked by At

I am new to Xcode and would like to check how do I code it such that I can use touch to move my object only in the y-coordinate.

Currently, I have programmed it to follow my touch, however it will follow both the x and y coordinate.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */
    if moving.speed > 0  {
        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)


            bird.physicsBody?.velocity = CGVectorMake(0, 0)
            bird.position = location

        }
    }else if canRestart {
        self.resetScene()
    }
}

I have tried searching for a few links online but I don't seem to understand it quite well.

1

There are 1 best solutions below

1
On

If you are just trying to move the "bird" up and down along the y axis from it's current x position, then use only the y value from the location:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */
    if moving.speed > 0  {
        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)

            // Just duplicate our old position
            var newPosition = bird.position
            // and change only the y value, leaving the x value as whatever it was initially set to. X will never change
            newPosition.y = location.y

            bird.physicsBody?.velocity = CGVectorMake(0, 0)
            bird.position = newPosition

        }
    }else if canRestart {
        self.resetScene()
    }
}

Check out the documentation on CGGeometry and, specifically, CGPoint.