Search code examples
iosswiftcollision-detectionscenekit

Detecting nodes on any side of a touched node


I have a game built using SceneKit and swift.

I have been struggling to figure out how to solve my problem.

I am trying to figure out how to detect nodes touching in my specific scenario. The image below demonstrates the issue I am facing... If a user touched any of the yellow cubes it would highlight that whole chain of yellow cubes. Same for the three red cubes on the bottom and the two red cubes on the top.

The way the game works is a user is given a shape of cubes. The shape can change position by the user swiping it various ways. Cubes may appear or get removed from the scene, so the position of the cubes can change easily. Finally a gravity function will pull the cubes down to the ground when the user swipes the shape, so if they twisted the image below to the right then it would end up as a brand new shape with most of the cubes in a new position.

Here is what I have tried:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
      let touch = touches.first!
      let location = touch.location(in: gameView)
      let hitList = gameView.hitTest(location, options: nil)

      if let hitObject = hitList.first {
         let node = hitObject.node

      //This is where I'm trying to detect the nodes and remove them
      gameScene.rootNode.childNodes.filter({ $0.name == node.color }).forEach({ $0.removeFromParentNode() })
   } 
}

The problem with my code is that it removes all of the cubes that are the same color as the hit cube.

enter image description here


Solution

  • I would not use SceneKit APIs to solve this problem.

    You have a game with cubes that can be arranged according to specific constraints. The application should have a model (abstract representation) of where each cube is, and the drawing of the cube is only a view of that model. Everything that involves your gameplay, including resolving which cubes are part of a chain of the same color, should be done on that abstract representation and then any update to the state of the cubes should be propagated to the SceneKit nod hierarchy.