Search code examples
iosswiftsprite-kitcollision-detectioncollision

My code detects collisions with a sprite but doesn't collide? - Swift


Here is my didBeginContact:

  func didBeginContact(contact: SKPhysicsContact) {


    let firstBody = contact.bodyA
    let secondBody = contact.bodyB


    let ballWasContacted = firstBody.categoryBitMask == PhysicsCat.Ball || secondBody.categoryBitMask == PhysicsCat.Ball
    let wallWasContacted = firstBody.categoryBitMask == PhysicsCat.Wall || secondBody.categoryBitMask == PhysicsCat.Wall
    let wallCheckWasContacted = firstBody.categoryBitMask == PhysicsCat.wallSpace || secondBody.categoryBitMask == PhysicsCat.wallSpace
    let scoreWasContacted = firstBody.categoryBitMask == PhysicsCat.Score || secondBody.categoryBitMask == PhysicsCat.Score
    let boundaryWasContacted = firstBody.categoryBitMask == PhysicsCat.Boundaries || secondBody.categoryBitMask == PhysicsCat.Boundaries


    if boundaryWasContacted {

        print("I collided with the boundary.")

        }

Here is my boundary sprite node:

  let boundary = SKSpriteNode(color: SKColor.whiteColor(), size: CGSize(width: 50, height: 150))
    boundary.name = "boundary"
    boundary.position = CGPoint(x: self.frame.width / 1.37, y: self.frame.height / 2)
    boundary.physicsBody = SKPhysicsBody(rectangleOfSize: boundary.size)
    boundary.physicsBody!.categoryBitMask = PhysicsCat.Boundaries
    boundary.physicsBody?.contactTestBitMask = PhysicsCat.Ball
    boundary.physicsBody?.collisionBitMask = PhysicsCat.Ball
    boundary.physicsBody!.dynamic = false
    boundary.physicsBody!.friction = 0
    boundary.physicsBody!.restitution = 1
    boundary.zPosition = 5
    self.addChild(boundary)

And finally here is my ball:

  Ball = SKSpriteNode(imageNamed: "Ball")
    Ball.size = CGSize(width: 38, height: 38)
    Ball.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
    Ball.physicsBody = SKPhysicsBody(circleOfRadius: Ball.frame.width / 2)
    Ball.physicsBody?.categoryBitMask = PhysicsCat.Ball
    Ball.physicsBody?.collisionBitMask = PhysicsCat.Wall
    Ball.physicsBody?.contactTestBitMask =  PhysicsCat.Wall | PhysicsCat.Score | PhysicsCat.wallSpace | PhysicsCat.Boundaries
    Ball.physicsBody?.affectedByGravity = false
    Ball.physicsBody?.dynamic = true
    Ball.physicsBody!.allowsRotation = true
    Ball.zRotation = CGFloat(M_PI)
    self.addChild(Ball)

When I come in contact with the boundary, it prints "I collided with the boundary", but I go straight through it. What exactly am I missing from my code to get the actual collision to occur between the ball and boundary?


Solution

  • Alter you didBeginContact to do something on contact.

    This question has been asked and the solution in this thread is by applying an Impluse in your didBeginContact.

    Currently, you only have a print statement happening. Try adding the relevant code like in this answer.

    https://stackoverflow.com/a/29433778/6407353