NovumCoder
NovumCoder

Reputation: 4697

SpriteKit/SKScene: How to draw from top-left instead from bottom-left?

As we know SKScene's origin is at bottom-left.

But i try a simple level loading from a file which contains a matrix of 0 and 1. While 0 is nothing, 1 means a wall (simple rectangle).

As the content of the file obviously goes from top-left to bottom-right, i would like to draw from top-left on the scene.

But my first character from file is drawn on bottom-left on the scene. I tried setting the scene's yScale to -1 hoping its inverting the y-axis, but that didn't work.

What is the cleanest way so on this SKScene i always start drawing from top-left? I still want to keep my anchorPoint at 0.5,0.5.

So drawing from top-left would be located at x=-widthOfScreen/2 and y=heightOfScreen/2

Upvotes: 5

Views: 1708

Answers (3)

richy
richy

Reputation: 2825

Similar to Alain T's answer but instead using a SKCameraNode with yScale = -1 so you don't need to override the addChild function or have an extra node layer.

let localCamera = SKCameraNode()
override func didMove(to view: SKView) {
    super.didMove(to: view)

    localCamera.yScale = -1
    localCamera.position = CGPoint(x: size.width/2, y: size.height/2)
    addChild(localCamera)
    self.camera = localCamera
// ...
}

Upvotes: 0

Hayden
Hayden

Reputation: 1870

I'm not sure if this is what you're going for, but if you just want to change the coordinate system around what you can do is create an extension for CGPoint, something like

//CGPoint+SpriteKit.swift
extension CGPoint {
    func flipCoordinates() -> CGPoint {
        return CGPoint(x: x, y: UIScreen.mainScreen().bounds.height - y)
    }
}

I think this should work, since your anchor point is (0.5, 0.5)

Upvotes: 6

Alain T.
Alain T.

Reputation: 42139

Since SKSpriteNode will let you flip its content using a scale of -1, you can place all your nodes under a master SKSpriteNode with a yScale of -1.

 final class GameScene: SKScene 
 {    
     var masterNode:SKSpriteNode! = nil
     override func addChild(node: SKNode) 
     {
        if masterNode == nil
        { 
           masterNode = SKSpriteNode()
           masterNode.position    = CGPoint(x:0, y:size.height)
           masterNode.anchorPoint = CGPointZero
           masterNode.yScale      = -1
           super.addChild(masterNode)        
        } 
        masterNode.addChild(node)
     }
 }

Note that you will need to keep the masterNode's y position aligned with the view size if/when the size changes.

Upvotes: 0

Related Questions