title: How to detect a collision between two objects in an Array (Sprite Kit)
body: <p>I have an array of Bullets and Enemies objects. I want the game to check each element in the arrays to see whether there was a collision between the two or not. If there was any collision, then damage that enemy and delete the bullet. Right now every time a bullet hits an enemy it decreases the health of ALL the enemies in the array, thus killing them all at once. How can I make it so that it only decreases the health of the enemy which I'm shooting at?</p>
  
  <pre><code> //This function handles our collision detection
      func didBegin(_ contact: SKPhysicsContact) {
          //print("COLLISIONS!")
          // If contact is with another object
          if contact.bodyA.categoryBitMask == pickupCategory &amp;&amp; contact.bodyB.categoryBitMask == playerCategory
          {
              displayText(text: "Picked up Pistol")
              player.setHasPistol(gotPistol: true)
              pistol.removeFromParent()
          }
  
          //Bullet hits an object
          if contact.bodyA.categoryBitMask == objectCategory &amp;&amp; contact.bodyB.categoryBitMask == bulletCategory
          {
              bulletCleanup(killNow: true)
              //print("BULLET HAS HIT THE PIPE!")
          }
  
          //Do collisions between bullets and enemies...
          for bullet in bulletList
          {
              for enemy in enemyList
              {
                  //if the enemy was hit have them take damage.
                  if contact.bodyA.categoryBitMask == enemyCategory &amp;&amp; contact.bodyB.categoryBitMask == bulletCategory
                  {
                      //deletes the bullet after hitting an object
                      bulletCleanup(killNow: true)
  
                      //apply damage
                      enemy.setHitPoints(setPoints: enemy.getHitPoints() - pistol.getDamage())
  
                      // print("BULLET HAS HIT THE enemy!!!!")
                  }
              }
          }
      }
  </code></pre>