zeeple
zeeple

Reputation: 5617

Swift nodeAtPoint difficulty

I am building a game in which the player drags a piece around the gameboard. I wish to know what are all of the nodes underneath that piece, and I am getting odd results. Here is the touchesMoves func:

    override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {

        let touch = touches.anyObject() as UITouch
        let location = touch.locationInNode(self.parent)

        self.position = location
        println("checker x: \(location.x)")
        println("node at point: \(self.nodeAtPoint(location))")
        println("nodes at point: \(self.nodesAtPoint(location))")

    }

The sprite moves around the board just fine, but what is reported as the nodeAtPoint is always the sprite being moved around (which kind of makes sense but is not useful. Any oddly, the nodesAtPoint is always reported as an empty array! How is this possible? What should I be doing differently?

Update: This continues to be a struggle. I want to keep the touch methods in the node itself, and not the scene. The most recent version of the touchesMoved is the following:

override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {

    // Turn off the touched bool:
    touched = false

    let touch = touches.anyObject() as UITouch
    let location = touch.locationInNode(self.parent)
    let loc = touch.locationInView(scene.view)
    let loc2 = touch.locationInNode(scene)

    self.position = location
    println("checker: \(loc2.x), \(loc2.y)")
    println("node at point: \(self.nodeAtPoint(loc2).name)")
    println("nodes at point: \(self.nodesAtPoint(loc2))")

}

The nodesAtPoint array continues to be empty with one really odd exception. When hovering near the center of the scene, I get this:

nodes at point: [ name:'(null)' accumulatedFrame:{{-30, -19.80000114440918}, {60, 39.600002288818359}}]

There is not shape node there that I am aware of! Why am I not detecting the nodes I pass over?

Upvotes: 0

Views: 2076

Answers (2)

zeeple
zeeple

Reputation: 5617

I discovered the answer to this. Essentially I was trying to detect nodesAtPoint on self, which in this case was the node being moved around the screen. Once I changed that to self.scene, the nodesAtPoint array populated as expected. So, to be clear:

println("nodes at point: \(self.nodesAtPoint(loc2))")

Needed to be changed to this:

println("nodes at point: \(self.scene.nodesAtPoint(loc2))")

Upvotes: 2

Andrey Gordeev
Andrey Gordeev

Reputation: 32459

If self is SKScene, try to change

let location = touch.locationInNode(self.parent)

to

let location = touch.locationInNode(self)

because SKScene's parent is nil

Upvotes: 1

Related Questions