Mark Tornej
Mark Tornej

Reputation: 175

How do I center array of nodes in view?

I have created a game board by programmatically drawing isometric tiles, then added them to an array. The nodes have have been places arbitrary to show the game board as much in the center as possible. Of course, this doesn't work when running on different devices. So, I'm looking for a way to always have the game board at the absolute center of the screen.

I had an idea about merging the nodes into one big... node? and then setting its center to the center of the view. Is that doable? How? Or is there a better or simpler way?

This is how I create a tile:

func newTile(size:CGSize) -> SKShapeNode {
    let shape = SKShapeNode()
    let path = UIBezierPath()
    path.move(to: CGPoint(x:0, y:size.height / 2.0))
    path.addLine(to: CGPoint(x:size.width / 2.0, y:0))
    path.addLine(to: CGPoint(x:0, y:-size.height / 2.0))
    path.addLine(to: CGPoint(x:-size.width / 2.0, y:0))
    path.close()

    shape.path = path.cgPath
    shape.lineWidth = 1.0
    shape.fillColor = SKColor.gray

    return shape
}

the function for placing the tile:

func tilePosition(col:Int, row:Int) -> CGPoint {
    let x = (CGFloat(row) * tileWidth  / 2.0) + (CGFloat(col) * tileWidth  / 2.0)
    let y = (CGFloat(col) * tileHeight / 2.0) - (CGFloat(row) * tileHeight / 2.0)
    return CGPoint(x: x-250, y: y)
}

... and adding to a board (I have deleted code here to simplify. This is just to give you an idea):

func createGameBoard(sceneView: SKScene) -> [[SKShapeNode]] {
    let size = CGSize(width: tileWidth, height: tileHeight)

    for row in 1...numRows {
        var colArray = [SKShapeNode]()


        for col in 1...numCols {
            let tile = newTile(size: size)
            tile.position = tilePosition(col: col, row: row)

            sceneView.addChild(tile)
            colArray.append(tile)
        }
            gameBoardArray.append(colArray)
    }
    return gameBoardArray
}

So, how do I place this thing smack in the middle of the view? That is, that the center tile is at the center of the screen and all the other tiles are aligned around it accordingly.

Upvotes: 0

Views: 43

Answers (1)

J. Mtz
J. Mtz

Reputation: 36

There are probably a thousand different ways to fix your issue, here is just a quick simple solution (another option could be to make the container a SKSpriteNode and set it's anchor to zero).

func arrangeButtonsInGrid(padding: Int) {

    var yPosition = -(rows / 2)

    for row in 0..<rows {

        var xPosition = -(columns / 2)

        for col in 0..<columns {
            tiles[col, row].position = CGPoint(x: padding * xPosition, y: padding * yPosition)
            xPosition += 1
        }

        yPosition += 1
    }
}

Upvotes: 1

Related Questions