Search code examples
iosswiftsprite-kittouchesbegan

Confusing reversed touch event in Swift


In my function

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
    for touch in touches{
        let touchLocation = touch.location(in: self.view)
        print("X: \(touchLocation.x) Y: \(touchLocation.y)")
    }
}

I get reversed Y value. If I click at the top I get ~0 value and if I click at the bottom I get high value. This makes my sprite im moving move in the wrong Y direction.

However if I remove '.view' in self.view it works as it should. Does anyone know why it's reversed when I use self.view?


Solution

  • As explained by Whirlwind in the comment below your question, this happened because with self you indicate SKScene (SpriteKit) and with self.view you use SKView (UIView subclass so UIKit system):

    UIKit coordinate system for iOS has its origin at the upper left of the drawing area, and positive values extend down and to the right from it.

    SpriteKit coordinate system uses the same coordinate system on both iOS and OS X, has the origin (0,0) in the lower-left corner, and the (1334,750) coordinate in the upper-right corner.