Reputation: 434
I have nodes falling from the top of the screen every second or so. When the player (at the bottom of the screen) collides with a falling node I want that particular node to be removed from the screen but have the other continue to fall.
I thought calling node.removeFromParent() might do this or might remove all of the nodes but nothing is happening regardless.
Here is what I have:
Making the nodes fall:
func makeMete() {
let meteTexture = SKTexture(imageNamed: "mete.png")
let movementAmount = arc4random() % UInt32(self.frame.width)
let meteOffset = CGFloat(movementAmount) - self.frame.width / 2
let moveMete = SKAction.move(by: CGVector(dx: 0, dy: -2 * self.frame.height), duration: TimeInterval(self.frame.height / 300))
let mete = SKSpriteNode(texture: meteTexture)
mete.position = CGPoint(x: self.frame.midX + meteOffset, y: self.frame.midY + self.frame.height / 2)
mete.physicsBody = SKPhysicsBody(circleOfRadius: meteTexture.size().height / 2)
mete.physicsBody!.isDynamic = false
mete.physicsBody!.contactTestBitMask = ColliderType.object.rawValue
mete.physicsBody!.categoryBitMask = ColliderType.object.rawValue
mete.physicsBody!.collisionBitMask = ColliderType.object.rawValue
mete.run(moveMete)
self.addChild(mete)
}
Detecting contact:
func didBegin(_ contact: SKPhysicsContact) {
if contact.bodyA.categoryBitMask == ColliderType.object.rawValue || contact.bodyB.categoryBitMask == ColliderType.object.rawValue {
player.physicsBody!.velocity = CGVector(dx: 0, dy: 0)
isUserInteractionEnabled = false
mete.removeFromParent()
}
.removeFromParent() seems to only work for me when there is one node on screen. Any more then it doesn't work.
Upvotes: 0
Views: 984
Reputation: 432
If you use mete it references the actual object mete and I assume there are many metes on screen. Try referencing the actual node from the physics body and removing that from the parent.
Replace
if contact.bodyA.categoryBitMask == ColliderType.object.rawValue || contact.bodyB.categoryBitMask == ColliderType.object.rawValue {
player.physicsBody!.velocity = CGVector(dx: 0, dy: 0)
isUserInteractionEnabled = false
mete.removeFromParent()
}
With
if contact.bodyA.categoryBitMask == ColliderType.object.rawValue {
contact.bodyA.node?.removeFromParent()
}else if contact.bodyB.categoryBitMask == ColliderType.object.rawValue {
contact.bodyB.node?.removeFromParent()
}
The .node gives you access to the actual instance in question.
Good Luck!
Upvotes: 4