如何创建一个将块添加到网格的函数?

How to create a function that will add blocks to a grid?

我有这段代码可以创建一个 15x12 的块网格,但我正在尝试访问每个块的索引并能够在给定索引处删除或添加块。我想我需要使用一个二维数组,但我不确定如何将这些块添加到一个数组中,这样我就可以很容易地在它们的索引处获取每个块。请评论您的任何提示或建议,谢谢!

         for i in 0...12{
            for j in 0...16{

            let block = SKSpriteNode(texture: blockImage, size: blockSize)
                block.position.x = block.frame.width/2 + CGFloat((64*j))
                block.position.y = frame.height - block.frame.height/2 - CGFloat((64*i))
                block.zPosition = 1
                
                addChild(block)
        }
        }

让我们按照你提出的想法去做。

第 1 步

如果我们将节点的索引(在键中)映射到节点(在值中),我们就可以创建一个字典。

struct Index: Hashable {
    let i: Int
    let j: Int
}
private var grid:[Index: SKNode] = [:]

第 2 步

现在将节点添加到父节点时,只需将 Index-Node 关系保存到字典中即可。

func addSprites() {
    let blockImage = SKTexture(imageNamed: "TODO")
    let blockSize = blockImage.size()

    for i in 0...12{
       for j in 0...16{
           let block = SKSpriteNode(texture: blockImage, size: blockSize)
           assert(grid[Index(i: i, j: j)] == nil)
           grid[Index(i: i, j: j)] = block // <------------
           block.position.x = block.frame.width/2 + CGFloat((64*j))
           block.position.y = frame.height - block.frame.height/2 - CGFloat((64*i))
           block.zPosition = 1
           addChild(block)
       }
    }
}

第 3 步

最后,您可以轻松删除给定索引的节点

func removeSprite(at index: Index) {
    guard let node = grid[index] else {
        debugPrint("No node found at index: \(index)")
        return
    }
    node.removeFromParent()
    grid[index] = nil
}

完整代码

class GameScene: SKScene {

    struct Index: Hashable {
        let i: Int
        let j: Int
    }
    private var grid:[Index: SKNode] = [:]

    func addSprites() {
        let blockImage = SKTexture(imageNamed: "TODO")
        let blockSize = blockImage.size()

        for i in 0...4{
           for j in 0...4{
               let block = SKSpriteNode(texture: blockImage, size: blockSize)
               assert(grid[Index(i: i, j: j)] == nil)
               grid[Index(i: i, j: j)] = block // <---
               block.position.x = block.frame.width/2 + CGFloat((64*j))
               block.position.y = frame.height - block.frame.height/2 - CGFloat((64*i))
               block.zPosition = 1
               addChild(block)
           }
        }
    }
    
    func removeSprite(at index: Index) {
        guard let node = grid[index] else {
            debugPrint("No node found at index: \(index)")
            return
        }
        node.removeFromParent()
        grid[index] = nil
    }

}

快速游乐场测试