SpriteKit: node Y position and touch Y position are not consistent
Brand new to SpriteKit and iOS in general. I am following a very simple SpriteKit tutorial and noticed that the Y position of the node is not the same as the Y position of the touch when it touched the same spot as the node. For example:
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
// add a text label at X: 100 and Y: 100
let labelNode = SKLabelNode(text: "X:100 Y:100")
labelNode.position.x = 100
labelNode.position.y = 100
labelNode.fontSize = 20.0
addChild(labelNode)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
// for each touch, print the X and Y positions
for touch: AnyObject in touches {
println("You touched at X: \(touch.locationInView(self.view!).x) and Y: \(touch.locationInView(self.view!).y)")
}
}
}
This adds text at X: 100 and Y: 100 that is at the bottom left of the scene (using the default scene.anchorPoint
). And when you touch, it prints X and Y where you touched.
The weird thing is , when I touch the center of the label node , the X position of 1.) node and 2.) where I touched are consistent. But Y is not. node Y is 100, but touch Y is 266. See screenshot below:
Can someone explain why this is?
I believe the culprit here locationInView()
is which returns the location in coordinate space of the base view, which is using a different coordinate system as your scene / nodes. The use is locationInNode()
to sort it.
From the documentation :
Returns the current location of the receiver in the given node's coordinate system.
Use the following:
println("You touched at X: \(touch.locationInNode(self).x) and Y: \(touch.locationInNode(self).y)")