touch location from all contacted bodies

68 Views Asked by At

Good Morning,

How can I get the location of a contact between two Physicsbody via allContactedBodies? Because of the structure of my App I cant use touchesBegan method from the Physicsbody but have to check it manually via allContactedBodies() from a Spritekit. But is there a method to get also the point where the touch occurred?

This is how I check for a contact but now I need also the position of the contact

if let unwrapped_allContactedBodies = spriteObject.spriteNode.physicsBody?.allContactedBodies() {
   if spriteObject.spriteNode.physicsBody?.allContactedBodies().count ?? 0 > 0 {
      return checkForContact(contactedBodies: unwrapped_allContactedBodies, parameter: value)
   } else {
     return 0.0
   }
} else {
  return 0.0
} ´´´


Any Ideas?
1

There are 1 best solutions below

0
Stefan Ovomate On

You can use the contact.contactPoint property. You will have to implement the SKPhysicsContactDelegate.

Example:

enum CollisionTypes: UInt32{
case nodeAColliding = 1
case nodeBColliding = 2
}

 class GameScene: SKScene, SKPhysicsContactDelegate  {


      override func didMove(to view: SKView) {

          physicsWorld.contactDelegate = self
      }

      func createNodes(){
        
         let nodeA = SKSpriteNode(imageNamed: "nodeAImage")
           nodeA.name = "nodeA"
           nodeA.zPosition = 2
           nodeA.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50   , height: 50))
           nodeA.position = //some CGpoint
           nodeA.physicsBody?.categoryBitMask = CollisionTypes.nodeAColliding.rawValue
           nodeA.physicsBody?.contactTestBitMask = CollisionTypes.nodeBColliding.rawValue
           nodeA.physicsBody?.collisionBitMask = CollisionTypes.nodeBColliding.rawValue
           addChild(nodeA)


         let nodeB = SKSpriteNode(imageNamed: "nodeBImage")
           nodeB.name = "nodeB"
           nodeB.zPosition = 2
           nodeB.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50   , height: 50))
           nodeB.position = //some CGpoint
           nodeB.physicsBody?.categoryBitMask = CollisionTypes.nodeBColliding.rawValue
           nodeB.physicsBody?.contactTestBitMask = CollisionTypes.nodeAColliding.rawValue
           nodeB.physicsBody?.collisionBitMask = CollisionTypes.nodeAColliding.rawValue
           addChild(nodeB)


      }
      

      func didBegin(_ contact: SKPhysicsContact){
          guard let contactedNodeA = contact.bodyA.node else {return}
          guard let contactedNodeB = contact.bodyB.node else {return}
     
           
          print(contact.contactPoint)
           
          if contactedNodeA.name == "nodeA"{
             //Do something
          }
           
          if contactedNodeA.name == "nodeB"{
             //Do something
          }
      }

  }

note: I have not tested this code in the compiler.