1

I have sprites moving across the screen, and if they are clicked then they disappear (i.e deleted).

I have overridden the touchesBegan func as follows:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("touch")
    let touch = touches.first!
    let location = touch.location(in: self)
    for child in self.children {

        if child.position == location {
            child.removeFromParent()
        }
    }
}

This doesn't seem to have any effect, can someone tell me where I am going wrong?

Andrew O'Rourke
  • 127
  • 1
  • 9
  • May I suggest a new title? – Shades Aug 02 '17 at 20:36
  • 1
    Ok. Changing it now. – Andrew O'Rourke Aug 02 '17 at 20:38
  • did you set touch interactions to enabled for them in the view or add a touch gesture on those sprites? – Lunarchaos42 Aug 02 '17 at 21:06
  • I think so, I added: self.sprite.isUserInteractionEnabled = true, sprite being the SKSpriteNode that I have stored in the object's class (being referenced as 'self' here). – Andrew O'Rourke Aug 02 '17 at 21:11
  • From what I am seeing doing a quick scan through google, you need to do something like for touch: Any in touches { let location = (touch as! UITouch).location(in: self) if let theName = self.atPoint(location).name { if theName == "Destroyable" { self.removeChildren(in: [self.atPoint(location)]) currentNumberOfShips?-=1 score+=1 } } with your sprite having a .name value of "Destroyable" – Lunarchaos42 Aug 02 '17 at 21:31

1 Answers1

2

In which class did you implement this method?

If it was in SKNode itself, you simply do:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    self.removeFromParent()

}

However, if this method is in SKScene, this way that was implemented would probably not work. Because child.position returns a point (x, y) where the touch was made. And you're trying to compare the touch point and position of the SKNode (center point), it's unlikely to work.

Instead of using this way, try using .nodeAtPoint, a method of SKScene.

For this you will need to put a value in the 'name' property of your SKNode:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("touch")
    let touch = touches.first!
    let positionInScene = touch.locationInNode(self)
    let touchedNode = self.nodeAtPoint(positionInScene)

    if let name = touchedNode.name
    {
        if name == "your-node-name"
        {
            touchedNode.removeFromParent()
        }
    }

}

Font: How do I detect if an SKSpriteNode has been touched

Sore
  • 176
  • 4