Search code examples
iosswiftsprite-kitskphysicscontact

Sprites not contacting properly


There's a ball and a paddle, the ball should be on the paddle and touching it but the ball never touches the paddle and stops before reaching the paddle, can anyone help me out?

enter image description here

import SpriteKit

class GameScene: SKScene ,SKPhysicsContactDelegate {

    let ballCategory:UInt32 = 0x1 << 0
    let bottomCategory:UInt32 = 0x1 << 1
    let paddleCategory:UInt32 = 0x1 << 2

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

        physicsWorld.contactDelegate = self


        let ball = SKSpriteNode(imageNamed: "ball")
        ball.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
        addChild(ball)

        ball.physicsBody = SKPhysicsBody(circleOfRadius: self.frame.size.width / 2)
        ball.physicsBody?.dynamic = true
        ball.physicsBody?.allowsRotation = false
        ball.physicsBody?.friction = 0
       // ball.physicsBody?.applyImpulse(CGVectorMake(2,-2))
        ball.physicsBody?.categoryBitMask = ballCategory
        ball.physicsBody?.contactTestBitMask = paddleCategory
        ball.physicsBody?.collisionBitMask = paddleCategory
        ball.physicsBody?.affectedByGravity = true

        let paddle = SKSpriteNode(imageNamed: "paddle")
        paddle.position = CGPointMake(CGRectGetMidX(self.frame), paddle.frame.size.height * 2)
        addChild(paddle)

        paddle.physicsBody = SKPhysicsBody(rectangleOfSize: paddle.frame.size)
        paddle.physicsBody?.affectedByGravity = false
        paddle.physicsBody?.dynamic = false
        paddle.physicsBody?.categoryBitMask = paddleCategory

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    }

    func didBeginContact(contact: SKPhysicsContact) {
            print("touched")

    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

Solution

  • The best way to determine where your nodes are making contact is to turn on Physics.

    Open GameViewController.swift and enter the following code:

    skView.showsPhysics =  true