0
votes

Obligatory: first time writing an app, relevant code is below. My code runs mostly as I want it to, but does not achieve my goal of dynamic object tracking.

I'm using Swift and Scenekit to build a simple puzzle game, similar to a 3d-version of candy crush.

I have a class Cube that extends SCNNode. On initialization, this class will randomly draw a 5x5 cube of SCNBoxes with each box being red, green, or blue (all 6 sides of a box are 1 color).

The goal of the game is to get the highest score by removing "chains" of SCNBoxes of like-colors. When a chain is removed, cubes should recognize gravity and drop to fill in the voids created by the removed-chain. This is where I need to dynamically track position. As the cubes fall into the gaps, their neighbors change.

My approach: build a struct CubeDetails that has properties var color: String and var location: SCNVector3. Next, build a dictionary masterCubeDict = [SCNNode: CubeDetails] that has all of the cubes of 1 color (the color is provided by a hittestresult).

Every time a user taps a cube, grab its color, refresh the masterCubeDict, and then use math on the SCNVector3 position to determine which cubes are neighbors.

I think my algorithm for finding 'cube neighbors' using math on the scnvector3 is where I'm off. There must be a better way for scenekit nodes to identity/find each other, right?

Also -- I would like the physics of the cubes to let them fall and have no bounce/sliding at all. They should only move straight up/down. Collisions should never happen. I thought I implemented that properly through friction, restituion, and mass of the cubes but I'm not getting the outcome I want.

class Cube

import SceneKit

class Cube : SCNNode {

    let cubeWidth:Float = 0.95
    let spaceBetweenCubes:Float = 0.05
    var cubecolor:UIColor = UIColor.black
    var masterCubeDict: [SCNNode: CubeDetails] = [:]

    struct CubeDetails {
        var color:String
        var position:SCNVector3
    }


    override init() {

        super.init()

        let cubeOffsetDistance = self.cubeOffsetDistance()

        var cubeColorString: String = ""

        var xPos:Float = -cubeOffsetDistance
        var yPos:Float = -cubeOffsetDistance
        var zPos:Float = -cubeOffsetDistance

        let xFloor:Float = -1.5
        let yFloor:Float = -1.5
        let zFloor:Float = -1.5
        let floorGeo = SCNBox(width: 20, height: 0, length: 20, chamferRadius: 0)
        let floor = SCNNode(geometry: floorGeo)
        floor.position = SCNVector3(x: xFloor, y: yFloor, z: zFloor)
        floor.name = "floor"
        floor.opacity = 0.0
        floor.physicsBody = SCNPhysicsBody(type: .kinematic, shape: nil)
        floor.physicsBody?.collisionBitMask = 1
        floor.physicsBody?.friction = 1.0
        self.addChildNode(floor)

        for _  in 0..<5 {
           for _ in 0..<5 {
                for _ in 0..<5 {
                    let cubeGeometry = SCNBox(width: CGFloat(cubeWidth), height: CGFloat(cubeWidth), length: CGFloat(cubeWidth), chamferRadius: 0)
                    let material = SCNMaterial()
                    material.diffuse.contents = randomColor()

                    //unwrap material (type any) and cast to uicolor for switch
                    if let unwrapColor: UIColor = material.diffuse.contents as? UIColor {

                        switch unwrapColor {
                        case UIColor.red:
                             cubeColorString = "red"
                        case UIColor.green:
                             cubeColorString = "green"
                        case UIColor.blue:
                             cubeColorString = "blue"
                        default:
                             cubeColorString = "black"
                        }
                    } else { print("Error unwrapping color") }

                    cubeGeometry.materials = [material, material, material, material, material, material]

                    let cube = SCNNode(geometry: cubeGeometry)
                    cube.name = cubeColorString
                    cube.physicsBody = SCNPhysicsBody(type: .dynamic, shape: nil)
                    cube.physicsBody?.restitution = 0.0
                    cube.physicsBody?.isAffectedByGravity = true
                    cube.physicsBody?.mass = 25.0
                    cube.physicsBody?.friction = 1.0
                    cube.physicsBody?.collisionBitMask = 1
                    cube.position = SCNVector3(x: xPos, y: yPos, z: zPos)

                    let details = CubeDetails(color: cubeColorString, position: cube.position)

                    //add cube details to the master dict
                    masterCubeDict[cube] = details

                    //print(masterCubeDict)


                    xPos += cubeWidth + spaceBetweenCubes
                    self.addChildNode(cube)
                }
                xPos = -cubeOffsetDistance
                yPos += cubeWidth + spaceBetweenCubes
            }
            xPos = -cubeOffsetDistance
            yPos = -cubeOffsetDistance
            zPos += cubeWidth + spaceBetweenCubes
        }
    }

    private func cubeOffsetDistance()->Float {
       return (cubeWidth + spaceBetweenCubes) / 2
    }

    private func randomColor() -> UIColor{
        var tmpColor: UIColor
        let num = Int.random(in:0...2)

        switch num {
        case 0:
            tmpColor = UIColor.red
        case 1:
            tmpColor = UIColor.blue
        case 2:
            tmpColor = UIColor.green
        default:
            tmpColor = UIColor.black
        }
        return tmpColor
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

GameViewController

import UIKit
import QuartzCore
import SceneKit

var myMasterCubeDict: [SCNNode: Cube.CubeDetails] = [:]

class GameViewController: UIViewController {

    let gameCube = Cube()

    override func viewDidLoad() {
        super.viewDidLoad()

        // create a new scene
        // let scene = SCNScene(named: "art.scnassets/ship.scn")!

        let scene = SCNScene()

        // create and add a camera to the scene
        let cameraNode = SCNNode()
        cameraNode.camera = SCNCamera()
        scene.rootNode.addChildNode(cameraNode)

        // place the camera
        cameraNode.position = SCNVector3(x: 2, y: 0, z: 20)

        // create and add a light to the scene
        let lightNode = SCNNode()
        lightNode.light = SCNLight()
        lightNode.light!.type = .omni
        lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
        scene.rootNode.addChildNode(lightNode)

        // create and add an ambient light to the scene
        let ambientLightNode = SCNNode()
        ambientLightNode.light = SCNLight()
        ambientLightNode.light!.type = .ambient
        ambientLightNode.light!.color = UIColor.darkGray
        scene.rootNode.addChildNode(ambientLightNode)

        // init cube
        myMasterCubeDict = gameCube.masterCubeDict
        scene.rootNode.addChildNode(gameCube)


        // retrieve the SCNView
        let scnView = self.view as! SCNView

        // set the scene to the view
        scnView.scene = scene


        // allows the user to manipulate the camera
        scnView.allowsCameraControl = true

        // show statistics such as fps and timing information
        scnView.showsStatistics = true

        // configure the view
        scnView.backgroundColor = UIColor.black


        // add a tap gesture recognizer
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        scnView.addGestureRecognizer(tapGesture)
    }

    @objc
    func handleTap(_ gestureRecognize: UIGestureRecognizer) {
        // retrieve the SCNView
        let scnView = self.view as! SCNView
        // check what nodes are tapped
        let p = gestureRecognize.location(in: scnView)
        let hitResults = scnView.hitTest(p, options: [:])
        // check that we clicked on at least one object
        if hitResults.count > 0 {
            // retrieved the first clicked object
            let result = hitResults[0]

            //get dict of same-color node
            var dictOfSameColor = findAndReturnChain(boi: result.node)
            //  print(dictOfSameColor)
            var finalNodes: [SCNNode] = [result.node]
            var resFlag = 1
            repeat {
                var xSame: Bool = false
                var ySame: Bool = false
                var zSame: Bool = false
                resFlag = 0
                for node in finalNodes {
                   // var nodeX = node.position.x
                    for (key, value) in dictOfSameColor {

                        if(abs(node.position.x - value.position.x) < 0.7)  {
                             xSame = true
                        }
                        if(abs(node.position.y - value.position.y) < 0.7) {
                             ySame = true
                        }
                        if(abs(node.position.z - value.position.z) < 0.7) {
                             zSame = true
                        }
                        //print("X-val: \(xDif) \nY-val: \(yDif) \nZ-val: \(zDif) \nColor: \(key.name) \n\n\n\n")
                        if (xSame && ySame ) {
                                if !(zSame) {
                                    if (abs((node.position.z-value.position.z)) < 2) {
                                    finalNodes.append(key)
                                    dictOfSameColor.removeValue(forKey: key)
                                    resFlag = 1
                                    }
                                }
                        }

                        if (xSame && zSame) {
                                  if !(ySame) {
                                    if (abs((node.position.y-value.position.y)) < 2) {
                                      finalNodes.append(key)
                                      dictOfSameColor.removeValue(forKey: key)
                                      resFlag = 1
                                    }
                                  }
                          }

                        if (ySame && zSame) {
                                  if !(xSame) {
                                    if (abs((node.position.x-value.position.x)) < 2) {
                                      finalNodes.append(key)
                                      dictOfSameColor.removeValue(forKey: key)
                                      resFlag = 1
                                    }
                                  }
                          }
                        xSame = false
                        ySame = false
                        zSame = false

                    }

                }

            //print(finalNodes)
            } while resFlag == 1

            //print(finalNodes)

            for node in finalNodes {
                if node.name != "floor" {
                node.removeFromParentNode()
                }
            }
            //IMPLEMENT: Reset dicts to current state of the cube
            myMasterCubeDict = updateMasterCubeDict(cube: gameCube)
            dictOfSameColor.removeAll()
        }




    }



    func findAndReturnChain(boi: SCNNode) -> [SCNNode:Cube.CubeDetails] {
        var ret: [SCNNode:Cube.CubeDetails] = [:]
        //find cubes with the same color
        for (key, value) in myMasterCubeDict {
            if value.color == boi.name {
                ret[key] = value
            }
        }

        return ret
    }

    func updateMasterCubeDict(cube: Cube) -> [SCNNode:Cube.CubeDetails] {
        myMasterCubeDict.removeAll()
        var newNode: SCNNode = SCNNode()
        var newDetails = Cube.CubeDetails(color: "", position: SCNVector3Zero)

        cube.enumerateChildNodes { (cube, stop) in
            newNode = cube
            if let newName = cube.name {
                newDetails.color = newName
            }
            newDetails.position = cube.position
            myMasterCubeDict[newNode] = newDetails
        }

        return myMasterCubeDict
    }


    override var shouldAutorotate: Bool {
        return true
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if UIDevice.current.userInterfaceIdiom == .phone {
            return .allButUpsideDown
        } else {
            return .all
        }
    }
}
1

1 Answers

0
votes

I did a game somewhat like this. You could probably get the math to work, but the way I did it was to map out each node and have an array containing its adjacent nodes. Doing it this way, I'm sure that when I remove a node and loop through its adjacent[array] nodes, then I got the right ones.

I don't subclass SCNNodes - some do, but I create the class I want that contains info about my node - I add the node to Scenekit there, that's separates the actual node from other work I may want to do with the class. Some nodes have a lot of detail that I may want to manage separately (multiple particle systems, movements, etc). Then I just keep my classes of nodes in an array and each class has direct access to it's own node.

Sorry - I don't know about the bounce, there are a lot of choices with the physics engine.