Search code examples
iosswiftsprite-kitskscene

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


Solution

  • 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)