Search code examples
sprite-kitpositionswift3

Why is my SpriteKitNode position not being displayed properly?


I'm new to SpriteKit and I'm following a tutorial that positions a SpritekitNode at the center near the bottom of the screen in portrait mode but regardless of the code I use, my object does not assume the position as discussed in the tutorial. I have looked at a couple other tutorials and they are pretty much the same thing with regards to the code to position the SpriteKitNode.

This is the only code I have in GameScene.swift:

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    var player:SKSpriteNode!

    override func didMove(to view: SKView) {

        player = SKSpriteNode(imageNamed: "Spaceship")
        player.xScale = 0.5
        player.yScale = 0.5

        player.position = CGPoint(x: self.frame.size.width / 2, y: player.size.height / 2 + 20)

        self.addChild(player)
    }

    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
    }
}

I have not added anything to GameScene.sks or made any changes to info.plist yet with the code above, mySpriteKitNode is displayed on the right center of the screen as shown in the picture below. The spaceship should be positioned near the red X.

Spaceship should be positioned near the red X

I have looked at several post regarding issues with positioning in SpriteKit but haven't found a solution for this.

If anyone could please explain what exactly am I doing wrong? Thanks


Solution

  • That is happening because the tutorial you are following is probably outdated. Earlier, when scene is loaded from a sks file, it had anchorPoint set to 0,0. Now , by default it is set to 0.5, 0.5.

    So you can either use your current code but set scene's anchor point to 0.0, 0.0, or to leave scene's anchorPoint as it is and set player's position property accordingly:

    //player.position.x should be 0 which is middle of the screen
    player.position.y = -frame.size.height / 2.0 + player.size.height/2.0 + 20.0