squarehippo10
squarehippo10

Reputation: 1945

Getting the position of an SKSpriteNode

I have an SKSpriteNode (call it gem) that uses an SKAction sequence to move across the screen. I'd like to get the exact location of gem when it collides with my player sprite.

All I know so far is what doesn't work. I've tried using firstBody.node?.position in didBeginContact but for some reason, that gives me the position when gem first loads and not where the collision took place. I've also tried using the position of my player since gem and player are pretty close together when they collide, - the result is okay, but not as accurate as I'd like.

I'm not sure the code will help, but here it is, just in case...

Animate gem

let moveGem = SKAction.moveByX(-distance - 25, y: 0.0, duration: NSTimeInterval(speedOfGem * distance))
let removeGem = SKAction.removeFromParent()
moveAndRemove = SKAction.sequence([moveGem, removeGem])

Attempt to get position

func didBeginContact(contact: SKPhysicsContact) {
   let firstBody = contact.bodyA
   let secondBody = contact.bodyB

   if firstBody.categoryBitMask == PhysicsCategory.gem && secondBody.categoryBitMask == PhysicsCategory.player 
   {
      print(firstBody.node!.position)
   }
}

Upvotes: 4

Views: 2215

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59496

Ok, this is not true

[...] that gives me the position when gem first loads and not where the collision took place.

Then what's happening?

The position of a node is expressed in relation to it's parent.

So if you have an SKScene and every node is its direct child then there's no problem.

However if you have multiple levels of nodes (like scene > nodeA > nodeB) then you need to convert the coordinate of the node from it's parent to the scene.

So how can I get the position?

In SpriteKit this can be done very easily

guard let scene = node.scene else { fatalError("Wait 😱 this node is not inside a scene!?") }
let position = node.convertPoint(node.position, toNode: scene)
print(position)

Upvotes: 5

Related Questions