So I created an SKSpriteNode subclass for my sprites. But whenever I retrieve the node(s) in the touched location (using nodes(at p: location), I can’t access the custom properties I that I had assigned to them earlier. Though I assume that’s because the retrieved node is of type SKSpriteNode as opposed to my custom type. So how would I go about either retrieving the node in my custom type or converting it to my custom type (while also retaining custom properties)?
Here's my subclass:
Here's where I initialized the sprites:
And here's where I retrieved the nodes that were tapped:
Any help would be greatly appreciated!
Here's my subclass:
Code Block swift class Gift: SKSpriteNode { var imageName: String var giftColor: Color init(imageName: String, giftColor: Color) { self.imageName = imageName self.giftColor = giftColor let texture = SKTexture(imageNamed: imageName) super.init(texture: texture, color: .clear, size: texture.size()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
Here's where I initialized the sprites:
Code Block swift func initializeGifts() { for i in 0...7 { var giftRow: [Gift] = [] for j in 0...7 { let color = randomColor() let x: Int = (115 + 77 * j) - Int(size.width) / 2 let y: Int = -(205 + 85 * i) + Int(size.height) / 2 giftRow.append(Gift(imageName: "gift_\(color.rawValue)", giftColor: color)) giftRow[j].name = "\(color.rawValue)Gift" giftRow[j].position = CGPoint(x: x, y: y) giftRow[j].size = CGSize(width: 50, height: 58) addChild(giftRow[j]) } gifts.append(giftRow) //`gifts` is a 2d array } }
And here's where I retrieved the nodes that were tapped:
Code Block swift override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } let location = touch.location(in: self) let touchedNodes = nodes(at: location) for node in touchedNodes { print(node.giftColor) //Error: Value of type 'SKNode' has no member 'giftColor' } }
Any help would be greatly appreciated!
You need to tell Swift compiler that the node actually is your custom class:
Code Block override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } let location = touch.location(in: self) let touchedNodes = nodes(at: location) for node in touchedNodes { if let gift = node as? Gift { //<- Check if node is a Gift or not. print(gift.giftColor) } } }