Search code examples
iosswifttouch-eventviewdidloadtouchesbegan

How to constantly get the x-position of an moving object in swift?


I have to buttons leftbutton, rightbutton both of them being SKSpriteNode(). When the user touches one of the buttons, there is a little ship that moves left and right as long as the user holds the touch.

Now I need a function or anything else that gives me the ship.position.x the whole time. I am stuck to try to make it print the position constantly. I can make it print everytime the button is touched but it only prints it once.

In my didMove I only created the buttons and the ship. So it should be rather irrelevant.

func moveShip (moveBy: CGFloat, forTheKey: String) {
    let moveAction = SKAction.moveBy(x: moveBy, y: 0, duration: 0.09)
    let repeatForEver = SKAction.repeatForever(moveAction)
    let movingSequence = SKAction.sequence([moveAction, repeatForEver])
    ship.run(movingSequence, withKey: forTheKey)
} 

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("\(ship.position.x)")

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

        if leftButton.contains(pointTouched) {

//          !! I MAKE IT PRINT THE POSITION HERE !!

            moveShip(moveBy: -30, forTheKey: "leftButton")
        }

        else if rightButton.contains(pointTouched) {
            moveShip(moveBy: 30, forTheKey: "rightButton")
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first{
        let pos = touch.location(in: self)
        let node = self.atPoint(pos)

        if node == aButton {

        } else {
            ship.removeAction(forKey: "leftButton")
            ship.removeAction(forKey: "rightButton")
        }
    }
}

In my code, the position is only printed once at the beginning of the touch and not printed until you release the touch and touch it again. Is there a possible way to do this with my code?


Solution

  • The touchesMoved function won't help you with your particular problem. You can check your frame constantly by creating a var timer = Timer() as instance variable.

    You then have to set up the timer and the function that is called when a specific amount of time is over. Do as following in your didMove function:

    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, 
            selector: #selector(detectShipPosition), userInfo: nil, repeats: true)
    

    As this will repeat itself every 0.01 seconds it will call the function detectShipPosition which you will implement OUTSIDE didMove.

    func detectShipPosition(){
        print("\(ship.position.x)")
    }