I'm animating a sprite, and when it touches another one, a physics contact function is called. Than, in this function, I'm trying to get the sprite with touched the other. Its body is bodyA but it's a SKPhysicsBody, and it can not be converted as a SKSpriteNode. Do you have any ideas?
The function is correctly called when contact, I just try to get the sprite which body makes the contact. The final idea is getting the actions attached to the sprite with I'm looking for but I suppose when you have the sprite it's easy.
let shootCategory: UInt32 = 0x1 << 0
let enemyCategory: UInt32 = 0x1 << 1
// Declaration of the SKPhysicsBody of the sprite which will touch the other one
sprite.physicsBody = SKPhysicsBody(circleOfRadius: (20))
sprite.physicsBody?.usesPreciseCollisionDetection = true
sprite.physicsBody?.categoryBitMask = shootCategory
sprite.physicsBody?.collisionBitMask = shootCategory | enemyCategory
sprite.physicsBody?.contactTestBitMask = shootCategory | enemyCategory
sprite.physicsBody?.affectedByGravity = false
// Declaration of the SKPhysicsBody of the sprite which will be touched
sprite.run(SKAction.group([moveAction, fadeInAction]))
sprite.physicsBody = SKPhysicsBody(circleOfRadius: (20))
sprite.physicsBody?.usesPreciseCollisionDetection = true
sprite.physicsBody?.categoryBitMask = enemyCategory
sprite.physicsBody?.collisionBitMask = shootCategory | enemyCategory
sprite.physicsBody?.contactTestBitMask = shootCategory | enemyCategory
sprite.physicsBody?.affectedByGravity = false
func didBegin(_ contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == enemyCategory) && (contact.bodyB.categoryBitMask == shootCategory){
// I tried this to get the sprite which the bodyB is attached to but it doesn't even build
let sprite: SKSpriteNode = sprite.contact.bodyB
contact.bodyA.removeAction(forKey: "moveToAction")
}
}
I finally found the solution with is really simple:
let Node = contact.bodyB.node as! SKSpriteNode