swiftcamerasprite-kitmovetouchesmoved

Swift SpriteKit: TouchesMoved doesn't update when finger stops and camera


I have a game where the player moves to a touch (and updates destination if touch moves). Everything works perfectly until the camera moves while the touch is not moving (the finger is resting on the screen so neither touchMoved nor touchesEnded is called) The player moves to the correct location in relation to where he started, but not in relation to the moving camera. (I don't want to save the location in the camera's frame of reference.. if that would even work, because then a single tap on the side of the screen would move the pl ayer to the end of the world.)

finger movement on screen

actual movement

desired movement

here's bare bones of code:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {            
        location = touch.location(in: self)            
        player.goto = location
        player.moving = true                
}}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {       
        let location = touch.location(in: self)       
         player.goto = location
         player.moving = true 
}}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
         player.goto = location
         player.moving = true            
}}   

override func update(_ currentTime: CFTimeInterval) {
    if player.position.x > w_screen/2 && player.position.x < (lab.size.width-w_screen/2) {
        cameranode.position.x = player.position.x
    }

    if player.moving == true {
        v = CGVector(dx: player.goto.x-player.position.x, dy: player.goto.y-player.position.y)
        d = sqrt(v.dx*v.dx + v.dy*v.dy)
        vel = 400*atan(d/20)/1.57
        if vel>1 { player.physicsBody!.velocity = CGVector(dx: v.dx*vel/d, dy: v.dy*vel/d) } else {
            player.moving = false
            player.physicsBody!.velocity = CGVector.zero
}}

any help would be appreciated.


Solution

  • if player.position.x > w_screen/2 && player.position.x < (lab.size.width-w_screen/2) {
            cameranode.position.x = player.position.x
        }
    

    This is why the camera is not moving where you want it, you are moving your camera to the player.position.x, but you never update your goto position.

    Just factor in how much the camera shifts and adjust the goto accordingly.

    if player.position.x > w_screen/2 && player.position.x < (lab.size.width-w_screen/2) {
    
            let camShiftX = player.position.x - cameranode.position.x
            let camShiftY = player.position.y - cameranode.position.y
    
            cameranode.position.x = player.position.x
            player.goto.x += camShiftX
            player.goto.y += camShiftY
    
        }