Search code examples
iosswiftsprite-kitskphysicsbody

Setting up a Ground node using SpriteKit?


I've been designing a game where I want the game to stop as soon as the ball makes contact with the ground. My function below is intended to set up the ground.

class GameScene: SKScene, SKPhysicsContactDelegate {

     var ground = SKNode() 

     let groundCategory: UInt32 = 0x1 << 0
     let ballCategory: UInt32 = 0x1 << 1

     //Generic Anchor coordinate points
     let anchorX: CGFloat = 0.5
     let anchorY: CGFloat = 0.5
     /*Sets the background and ball to be in the correct dimensions*/

     override init(size: CGSize) {
         super.init(size: size)

         //Create the Phyiscs of the game
         setUpPhysics()  

         setUpGround()   

         setUpBall()
    }

    func setUpPhysics() -> Void {
        self.physicsWorld.gravity = CGVectorMake( 0.0, -5.0 )
        self.physicsWorld.contactDelegate = self
    }

     func setUpGround() -> Void {
        self.ground.position = CGPointMake(0, self.frame.size.height)
        self.ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, self.frame.size.height)) //Experiment with this
        self.ground.physicsBody?.dynamic = false

        self.ground.physicsBody?.categoryBitMask = groundCategory    //Assigns the bit mask category for ground
        self.ball.physicsBody?.contactTestBitMask = ballCategory  //Assigns the contacts that we care about for the ground

        /*Added in*/
        self.ground.physicsBody?.dynamic = true

        self.ground.physicsBody?.affectedByGravity = false
        self.ground.physicsBody?.allowsRotation = false
        /**/

        self.addChild(self.ground)
    }

    func setUpBall() -> Void {

        ball.anchorPoint = CGPointMake(anchorX, anchorY)

        self.ball.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2)

        self.ball.name = "ball"
        self.ball.userInteractionEnabled = false

        ball.physicsBody?.usesPreciseCollisionDetection = true

        self.ball.physicsBody?.categoryBitMask = ballCategory    //Assigns the bit mask category for ball
        self.ball.physicsBody?.collisionBitMask = wallCategory | ceilingCategory //Assigns the collisions that the ball can have
        self.ball.physicsBody?.contactTestBitMask = groundCategory   //Assigns the contacts that we care about for the ball

        addChild(self.ball)  //Add ball to the display list
    }

The problem I am noticing is that when I run the iOS Simulator, the Ground node is not being detected. What am I doing wrong in this case?


Solution

  • Your ballCategory should be assigned to self.ground.contactBitMask not the ball.