Tiptonix Beats Tiptonix Beats - 5 months ago 9
iOS Question

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?

Answer

Well now the boundary is being moved by the ball. SO, to stop that let

        physicsBody?.pinned = true
        physicsBody?.allowsRotation = false
        physicsBody?.affectedByGravity = false

It seems this question has been asked and there's a better solution in this thread though by applying an Impluse in your didBeginContact and just going back to dynamic = false

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

Comments