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

问题描述 投票:0回答:1

我有这段代码创建了一个 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)
        }
        }

swift sprite-kit skspritenode
1个回答
1
投票

让我们遵循您提出的想法。

步骤1

我们可以创建一个字典,将节点(在键中)的索引与节点(在值中)进行映射。

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

步骤2

现在,当您将节点添加到父节点时,只需将索引节点关系保存到字典中即可。

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 = block.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 = block.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
    }

}

快速游乐场测试

© www.soinside.com 2019 - 2024. All rights reserved.