Search code examples
iosswiftsprite-kitskspritenodeskphysicsbody

Adding Physic Bodies to Spritekit Nodes


I am making a basic game on iOS using Xcode 7 and Swift 2. I am trying to add physic bodies to nodes. On the user's character, the physic body runs fine (nothing crashes and it runs the same). However, when adding physic bodies to obstacles, the obstacle does not appear... Here is my code for the obstacle:

        let random = Int(arc4random_uniform(4))
        var objectTexture = SKTexture()
        var object = SKSpriteNode()
        if random == 0 {
            objectTexture = SKTexture(imageNamed: "coin")
            object = SKSpriteNode(texture: objectTexture)

            object.physicsBody = SKPhysicsBody(rectangleOfSize: objectTexture.size())
            object.physicsBody!.categoryBitMask = ColliderType.Coin.rawValue
            object.physicsBody!.contactTestBitMask = ColliderType.Coin.rawValue
            object.physicsBody!.collisionBitMask = ColliderType.Coin.rawValue

        }
        if random != 0 {
            objectTexture = SKTexture(imageNamed: "fryingPan")
            object = SKSpriteNode(texture: objectTexture)

            object.physicsBody = SKPhysicsBody(rectangleOfSize: objectTexture.size())
            object.physicsBody!.categoryBitMask = ColliderType.Obstacle.rawValue
            object.physicsBody!.contactTestBitMask = ColliderType.Obstacle.rawValue
            object.physicsBody!.collisionBitMask = ColliderType.Obstacle.rawValue

        }
        //Setting up object

Using this code, the object does not appear on to the screen. When I comment out the physic body lines, however, the object appears on the screen as directed. Does anyone know where I might be going wrong? Thanks for your help.


Solution

  • Set

    object.physicsBody.affectedByGravity = false

    I guess the gravity moves your obstacles out of the screen