Martin Jones Martin Jones - 1 month ago 25
Swift Question

Swift 3 Beginner - Position Assets in Scene

I am a complete beginner at Swift 3 and programming in general so this will be an incredibly basic question.

I have been following tutorials and am currently positioning a SpriteNode using CGPoint. The tutorial recommends the following to position the Node centrally at the bottom of the screen:

Ground.position = CGPoint(x: self.frame.width / 2, y: 0)

However, that causes it to stick to the top-right of the screen.

When I use the following code:

Ground.position = CGPoint(x: 0 - self.frame.width / 2, y: 0 - self.frame.height / 2)

It positions at the bottom-centre as intended.

I do not understand why this happens as there is very little else done in the tutorial at this point to cause the error.

Nik Nik

Set the anchorPoint of the scene to the bottom left corner at the beginning of your didMove(toView: SKView) (or in GameViewController):

scene.anchorPoint = CGPoint(x: 0, y: 0)

Keep in mind that everything you place on the scene is placed based on the anchorPoint. So with this anchorPoint, the origin of your scene is the bottom left corner.

Also note that if you're using .AspectFill as your sceneScaleMode, you don't have to use self.frame and instead set the scene size to 768x1024 (portrait)/ 1024x768 (landscape) then just use number values within the scene size.

Additionally, there are advantages of setting your scenes anchorPoint to the centre:

scene.anchorPoint = CGPoint(x: 0.5, y: 0.5)

This makes it easier to fit the scene into iPad size as well as iPhone, and also simplifies centering nodes.