I'm having trouble centering a SKNode on my main scene. This (photo below) is a SKNode that contains 16 SKLabelNodes. In the code, it sits at position (0, 0), but as you can see on the image, it doesn't seem to be centered. Also, Apple documentation doesn't say anything about anchorPoint on SKNodes.
So, how can I center a SKNode on a scene?
This is the code.
I have a struct that stores the labels in an array. I init them to 0.
struct NumberButtonsMatrix {
let rows: Int, columns: Int
var grid: [NumberButton]
init(rows: Int, columns: Int) {
grid = [NumberButton]()
self.rows = rows
self.columns = columns
for _ in 0..<(rows*columns) {
let button = NumberButton(number: 0)
grid.append(button)
}
}
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
func indexIsValid(index :Int) -> Bool {
return index >= 0 && index < rows*columns
}
subscript(row: Int, column: Int) -> NumberButton {
get {
assert(indexIsValid(row: row, column: column), "Index not valid")
return grid[(row*columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index not valid")
grid[(row*columns) + column] = newValue
}
}
subscript(index: Int) -> NumberButton {
get {
assert(indexIsValid(index: index), "Index not valid")
return grid[index]
}
set {
assert(indexIsValid(index: index), "Index not valid")
grid[index] = newValue
}
}
I also have this function in the struct that arranges the nodes in a grid. (The subscript is also on the struct but I don't think it's necessary to put it here)
func arrangeButtonsInGrid(separation: Int) {
for i in 0..<rows {
for j in 0..<columns {
self[i, j].position = CGPoint(x: -separation*i, y: separation*j)
}
}
}
Then, I have a class called GameBoard that is a subclass of SKNode where all the SKLabels are at.
class GameBoard: SKNode {
var numberButtons: NumberButtonsMatrix
init(rows: Int, columns: Int) {
numberButtons = NumberButtonsMatrix(rows: rows, columns: columns)
super.init()
numberButtons.arrangeButtonsInGrid(separation: 144)
for i in 0..<(rows*columns) {
numberButtons[i].number = i
self.addChild(numberButtons[i])
}
}
Finally, I add them on my scene.
var gameBoard = GameBoard(rows: 4, columns: 4)
gameBoard.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
self.addChild(gameBoard)