3
votes

Totally new to SpriteKit, and iOS development in general. I'm following a very basic SpriteKit tutorial, and noticed that a node's Y position isn't the same as a touch's Y position, when touched in 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, which is the bottom left of the scene (using the default scene.anchorPoint). And when you touch, it prints the X and Y of where you touched.

The weird thing is, when I touch the center of the label node, the X position of 1.) the node and 2.) where I touched are consistent. But the Y's are not. The node's Y is 100, but the touch's Y is 266. See screenshot below:

screenshot

Can someone explain why this is?

1

1 Answers

2
votes

I believe the culprit here is locationInView(), which returns a location in the coordinates space of the underlying view, which uses a different coordinate system as your scene/nodes. Using locationInNode() should sort this out.

From the documentation:

Returns the current location of the receiver in the coordinate system of the given node.

Use as follows:

println("You touched at X: \(touch.locationInNode(self).x) and Y: \(touch.locationInNode(self).y)")