Swift - Random collisions are not detected

  1. last year
    Edited last year by iOscar

    In my game, I use SKSprite. Some collisions are not detected. I did 10 tries, collisions are working well but about 25% of collisions that are supposed to be detected are not detected. I have NO idea why, I tried many things. Collisions are only with nodes of the same category.

    I have no idea why randomly some collisions are not made when I can obviously see them, do you have any idea? Thanks for your help.

    Here is the code of didBeginContact:

        func didBeginContact(contact: SKPhysicsContact) {
    
            var firstBody: SKPhysicsBody = contact.bodyA
            var secondBody: SKPhysicsBody = contact.bodyB
    
            if firstBody.categoryBitMask == secondBody.categoryBitMask {
                
                    listContacts.append([firstBody.node!,secondBody.node!])
                }
    
            }
        }

    Here is the code of didEndContact:

    func didEndContact(contact: SKPhysicsContact) {
            
            var firstBody: SKPhysicsBody = contact.bodyA
            var secondBody: SKPhysicsBody = contact.bodyB
    
            if contact.bodyA.categoryBitMask == contact.bodyB.categoryBitMask {
                
                for i in listContacts{
    
                    if (i.contains(firstBody.node!) && i.contains(secondBody.node!)){
                        
                        let findIndex = listContacts.indexOf { $0 == i }
                        listContacts.removeFirst(findIndex!) 
                    }
                }
                
            }

    Finally when I declare a new SKSpriteNode I set this:

       rectangle.physicsBody = SKPhysicsBody(rectangleOfSize: rectangle.size)
        rectangle.physicsBody?.dynamic = true 
        rectangle.physicsBody?.collisionBitMask = PhysicsCategory.None

    usesPreciseCollisionDetection = true doesn't change anything so I don't use usePrecisionCollisionDetection

    Every SKSpriteNode has his categoryBitmask and contactTestBitmask equal because only same SKSpriteNodes are supposed to collide.

    Also:

       physicsWorld.gravity = CGVectorMake(0, 0)
        physicsWorld.contactDelegate = self

    Finally here is a short video of my game if you want to understand easily what happens (problem of collisions are between rectangles)

    video

or Sign Up to reply!