I am trying to code a word collision detection game.
The problem is that before I add rectangle as a background of my words, all of my codes are working, I can detect the collision and take action. but after add rectangle, I have to change my parents of the word and I add it as the child of background.
This the function that I create word:
func giveWords() {
randomIndex = Int.random(in: 0 ..< lastWords.count)
word = SKLabelNode(text: "\(lastWords[randomIndex])")
lastWords.remove(at: randomIndex)
word.fontSize = 17
word.name = "word"
word.fontName = "HelveticaNeue-Bold"
backgroundWord = SKShapeNode(rect: CGRect(x: 0, y: 0, width: (word.frame.width + 3), height: (word.frame.height + 2)), cornerRadius: 4)
word.physicsBody? = SKPhysicsBody(rectangleOf: self.size)
word.physicsBody?.collisionBitMask = 0
word.physicsBody?.contactTestBitMask = 0
word.physicsBody?.categoryBitMask = 1
word.physicsBody?.affectedByGravity = false
word.physicsBody?.isDynamic = false
word.position = CGPoint(x:(backgroundWord.position.x + word.frame.width/2 + 1 ), y: (backgroundWord.position.y) + 4)
let number = Int.random(in: 1 ..< 9)
backgroundWord.position = CGPoint(x: (50 * number), y: 450)
word.zPosition = 3
backgroundWord.zPosition = 3
backgroundWord.addChild(word)
addChild(backgroundWord)
}
and this is the code that I check collision:
func checkCollision() {
enumerateChildNodes(withName: "word") { (node, _) in
let word = node as! SKLabelNode
if self.basketNode.frame.intersects(word.frame) {
if self.similarWord.contains(word.text!) {
self.score += 1
self.scoreLabel.text = "\(self.score)"
self.takeWord.append(word.text!)
self.run(self.trueSound)
self.backgroundWord.removeFromParent()
} else {
self.run(self.falseSound)
self.health -= 1
self.healthLabel.text = "HP: \(self.health)"
self.backgroundWord.removeFromParent()
}
}
}
}
I tried physics collision but I did not handle, so I chose this algorithm.
After function called, self.basketNode.frame.intersects(word.frame) returns false, this means collision is not detected.
I couldn't handle why collision is not detected.
Thanks in advance!
I solved it, here is the answer and reason.
The reason behind it is, and the reason why I did not detect
self.basketNode.frame.intersects(word.frame)is simple.I tried to detect word's frame intersection but I should detect its parent which is the background. So I changed the word to the background and after that create a let that help me to access word. Here is the answer btw...
btw I got helped from Apple documentation
https://developer.apple.com/documentation/spritekit/sknode/1483024-enumeratechildnodes
Thanks for your effort, I am continuing my project.