必填:首次编写应用程序,相关代码如下。我的代码主要按照我希望的方式运行,但没有实现动态对象跟踪的目标。

我正在使用Swift和Scenekit构建一个简单的益智游戏,类似于3D版本的Candy Crush。

我有一个class Cube那个extends SCNNode。初始化时,此类将随机绘制一个5x5的SCNBoxes立方体,每个方框为红色,绿色或蓝色(方框的所有6面均为1种颜色)。

该游戏的目标是通过删除相似颜色的SCNBoxes的“链”来获得最高分数。卸下链条后,立方体应识别重力并掉落以填充由卸下的链条造成的空隙。这是我需要动态跟踪位置的地方。当立方体掉入空隙中时,它们的邻居会发生变化。

我的方法:构建具有属性struct CubeDetailsvar color: Stringvar location: SCNVector3。接下来,构建具有所有1种颜色的多维数据集的字典masterCubeDict = [SCNNode: CubeDetails](颜色由hittestresult提供)。

每次用户点击一个多维数据集时,获取其颜色,刷新masterCubeDict,然后在SCNVector3位置上使用数学运算来确定哪些多维数据集是相邻的多维数据集。

我认为我要使用scnvector3上的数学算法来查找“多维数据集邻居”的算法。场景套件节点必须有一种更好的方式来相互标识/查找,对不对?

另外-我希望立方体的物理性质让它们掉落并且完全没有弹跳/滑动。它们只能直线向上/向下移动。碰撞永远不会发生。我以为我可以通过摩擦,恢复和立方体质量适当地实现这一点,但我没有得到想要的结果。

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
        }
    }
}

最佳答案

我做了这样的游戏。您可能可以使数学起作用,但我的方法是映射每个节点并拥有一个包含其相邻节点的数组。这样,我确定当我删除一个节点并遍历其相邻的[array]节点时,便可以得到正确的节点。

我不对SCNNodes进行子类化-有些确实这样做,但是我创建了我想要的包含有关节点信息的类-我将该节点添加到Scenekit中,这将实际的节点与我可能要对该类进行的其他工作分开。有些节点有很多细节,我可能要分别管理(多个粒子系统,运动等)。然后,我只是将节点的类保留在数组中,每个类都可以直接访问它自己的节点。

抱歉-我不知道弹跳,物理引擎有很多选择。

10-04 23:36