У меня SKSpriteNode
движется вокруг SKTileMapNode
. SKSpriteNode
перемещается к плитке, к которой прикасается пользователь. В приведенном ниже коде консоль выводит «row: 0, column: 0» до и после перемещения игрока SKSpriteNode
. Почему это происходит? Разве второй оператор печати не должен печатать новую позицию игрока?
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var player: SKSpriteNode!
var grid: SKTileMapNode!
var touchLocation: CGPoint = .zero
override func didMove(to view: SKView) {
self.backgroundColor = .white
loadSceneNodes()
}
func loadSceneNodes() {
setupGrid()
setupCharacter()
}
func setupGrid() {
let columns = 10
let rows = 10
let size = CGSize(width: 64, height: 64)
guard let tileSet = SKTileSet(named: "Ground Tiles") else {
fatalError("Tile set not found")
}
grid = SKTileMapNode(tileSet: tileSet, columns: columns, rows: rows, tileSize: size)
addChild(grid)
grid.name = "grid"
let tileGroups = tileSet.tileGroups
guard let dirtLightTile = tileGroups.first(where: {$0.name == "DirtLight Tile"}) else {
fatalError("No DirtLight tile definition found")
}
guard let dirtDarkTile = tileGroups.first(where: {$0.name == "DirtDark Tile"}) else {
fatalError("No DirtDark tile definition found")
}
for column in 0...columns {
for row in 0...rows {
if (row % 2 == 0) && (column % 2 == 0) {
grid.setTileGroup(dirtLightTile, forColumn: column, row: row)
} else if (row % 2 != 0) && (column % 2 != 0) {
grid.setTileGroup(dirtLightTile, forColumn: column, row: row)
} else {
grid.setTileGroup(dirtDarkTile, forColumn: column, row: row)
}
}
}
}
func setupCharacter() {
player = SKSpriteNode(imageNamed: "knight")
let height = player.size.height
let scaleFactor = grid.tileSize.height / height
player.setScale(scaleFactor)
player.position = grid.centerOfTile(atColumn: 0, row: 0)
addChild(player)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
touchLocation = touch.location(in: self)
let touchRow = grid.tileRowIndex(fromPosition: touchLocation)
let touchCol = grid.tileColumnIndex(fromPosition: touchLocation)
let touchedNodes = self.nodes(at: touchLocation)
for node in touchedNodes {
if node.name == "grid" {
print(getRowCol(character: player))
let newTile = grid.centerOfTile(atColumn: touchCol, row: touchRow)
let move = SKAction.move(to: newTile, duration: 0.5)
player.run(move)
print(getRowCol(character: player))
}
}
}
func getRowCol(character: SKSpriteNode) -> (row: Int, column: Int) {
let row = grid.tileRowIndex(fromPosition: character.position)
let col = grid.tileColumnIndex(fromPosition: character.position)
return (row, col)
}
}