Search code examples
iosswiftsprite-kitsift

Tilting Spaceship left and right in Spritekit


I have built a small Space Shooter game like so many other have already :-D and I got everything nailed down except for the tilting images of the Space ship.

I use 3 images - left, center and right - and while I can get the images to turn left and right the problem remains that it only does so when actually touching the left/right side of the screen and the center image never shows at all, which it should if the ship does not move.

Be great if someone could shine a light on that one for me please...

Here is my code for touchesMoved:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch: AnyObject in touches{

        let pointOfTouch = touch.location(in: self)
        let previousPointOfTouch = touch.previousLocation(in: self)

        let amountDragged = pointOfTouch.x - previousPointOfTouch.x

        if currentGameState == gameState.inGame{
        player.position.x += amountDragged
        }

        if player.position.x > gameArea.maxX - player.size.width/2{
            print("Ship turning Right") //Log print to check if it works
            player.texture = SKTexture(imageNamed: "playerShipRight")
            player.position.x = gameArea.maxX - player.size.width/2
        }

        if player.position.x < gameArea.minX + player.size.width/2{
            print("Ship turning Left") //Log print to check if it works
            player.texture = SKTexture(imageNamed: "playerShipLeft")
            player.position.x = gameArea.minX + player.size.width/2
        }
    }
}

Solution

  • I assume from your comments that the ship is firing all the time you touch the screen, so you can't use touchesEnded to center the ship because you may not want to move but you still want to shoot.

    A simple solution would be to revert to the the center image if ship.position = pointOfTouch or if amountDragged = 0 or some small value.

    A more sophisticated approach would be to have an array of perhaps 7 ship textures, representing the ship moving left quickly, medium speed, slowly, stationary, right slowly, right medium speed and right quickly. You could then used amountDragged to index into this array for the correct texture.

    You could also use touchesEnded to implement a 'non-firing, non-moving' texture if you wanted to.