How do I detect which SKSpriteNode has been touched

后端 未结 2 809
猫巷女王i
猫巷女王i 2020-11-28 14:35

I find a similar question, but I am trying to detect and identify which Sprite the user touch, and I don\'t know how to do that. This is my variable:

var sp         


        
2条回答
  •  伪装坚强ぢ
    2020-11-28 15:19

    First, you need another way to create the sprite, here are a way:

    let spriteA = SKSpriteNode(imageNamed: "a")
    scene.addChild(spriteA)
    let spriteB = SKSPriteNode(imageNamed: "b")
    scene.addChild(spriteB)
    ...and so on...
    

    Now we needs to set a name for the sprite so we can know which node is tapped later. To add a name for a sprite just do this:

    spriteNode.name = "name of the sprite"
    

    Putting this code in the above example will look something like this:

    let spriteA = SKSpriteNode(imageNamed: "a")
    spriteA.name = "a"
    scene.addChild(spriteA)
    let spriteB = SKSPriteNode(imageNamed: "b")
    spriteB.name = "b"
    scene.addChild(spriteB)
    ...and so on...
    

    To detect touches put this into your SKScene subclass:

    override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
        let touch = touches.first as UITouch!
        let touchLocation = touch.locationInNode(self)
        let targetNode = nodeAtPoint(touchLocation) as! SKSpriteNode
    }
    

    The targetNode is the node you tapped.

    If you wants to get the name of the sprite you can use targetNode.name.

提交回复
热议问题