Question

I just startet playing around with swift and want to execute something if any of my nodes collide. Obviously I didn't get that working but I Have no clue why. Read the Documentation a few times but it's mostly written for Objective-C and honestly I think I did not understand it.

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

  var eyeset = 0
  var eyes: [SKSpriteNode] = []

  override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
      /* Called when a touch begins */

      for touch: AnyObject in touches {

          let location = touch.locationInNode(self)

          if (eyeset < 9) {

              eyes.insert(SKSpriteNode(imageNamed: "eye"), atIndex: eyeset)
              eyes[eyeset].xScale = 0.25
              eyes[eyeset].yScale = 0.25
              eyes[eyeset].position = location
              eyes[eyeset].physicsBody = SKPhysicsBody(circleOfRadius: eyes[eyeset].size.height/2)
              eyes[eyeset].physicsBody.collisionBitMask = 1
              eyes[eyeset].physicsBody.dynamic = true
              eyes[eyeset].physicsBody.affectedByGravity = true

              self.addChild(eyes[eyeset])
              eyeset++
          }
          else if (eyeset < 10) {

              eyes.insert(SKSpriteNode(imageNamed: "eye"), atIndex: eyeset)
              eyes[eyeset].xScale = 0.5
              eyes[eyeset].yScale = 0.5
              eyes[eyeset].position = location
              eyes[eyeset].physicsBody = SKPhysicsBody(circleOfRadius: eyes[eyeset].size.height/2)
              eyes[eyeset].physicsBody.collisionBitMask = 1
              eyes[eyeset].physicsBody.dynamic = true
              eyes[eyeset].physicsBody.angularDamping = 1
              eyes[eyeset].physicsBody.affectedByGravity = false

              self.addChild(eyes[eyeset])
              eyeset++
          }
          else {
              eyes[eyeset-1].runAction(SKAction.moveTo(location, duration: 0.25))
          }
      }
  }

  func didBeginContact(contact: SKPhysicsContact!) {
      println("Muttermäßig")
  }
}
Was it helpful?

Solution

For contact detection to work, you have to set the contactTestBitMask property of SKPhysicsBody.

eyes[eyeset].physicsBody.contactTestBitMask = 1

CollisionBitMask specifies which bodies can collide with each other in the physics environment, whereas the contactTestBitMask defines the categories of physics bodies for which the contact delegate methods will get called when the node intersects with them.

Read up on the documentation here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top