我想创建一个场景,在该场景中,我有一些按钮可以在SKTileMapNode内部将光标从图块移动到图块。我在Spritekit场景编辑器的外部.sks
文件中创建了一个10x8的SKTileMapNode。为了将光标的位置与图块完全相同,我想注册图块的特定列和行索引,然后找出其位置。使用功能numberOfColumns
和tileRowIndex
给我的值比numberOfRows
和tileRowIndex
高,它们的值分别是10和8。由于这个问题,我的光标显示在错误的位置。甚至在任何瓷砖位置都没有对齐。
class Spielfeld: SKScene {
var x: Int = 0 // Anzahl Felder in x-Richtung
var y: Int = 0 // Anzahl Felder in y-Richtung
var tilemap: SKTileMapNode = SKTileMapNode()
var up: SKSpriteNode = SKSpriteNode()
var down: SKSpriteNode = SKSpriteNode()
var left: SKSpriteNode = SKSpriteNode()
var right: SKSpriteNode = SKSpriteNode()
var cursor: SKSpriteNode = SKSpriteNode(imageNamed: "Cursor1Blue")
override func sceneDidLoad() {
up = self.childNode(withName: "Up") as! SKSpriteNode
down = self.childNode(withName: "Down") as! SKSpriteNode
left = self.childNode(withName: "Left") as! SKSpriteNode
right = self.childNode(withName: "Right") as! SKSpriteNode
tilemap = self.childNode(withName: "Tile Map Node") as! SKTileMapNode
cursor.position = tilemap.centerOfTile(atColumn: 5, row: 5)
cursor.zPosition = 0.1
self.addChild(cursor)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = touches.first! as UITouch
let positionInScene = touch.location(in: self)
let touchedNode = self.atPoint(positionInScene)
print(touchedNode.name!)
if(touchedNode.name == "Tile Map Node") {
let map = touchedNode as! (SKTileMapNode)
print(map.tileColumnIndex(fromPosition: positionInScene)) // higher than 10
print(map.tileRowIndex(fromPosition: positionInScene)) // higher than 8
print(map.numberOfColumns) // 10
print(map.numberOfRows) // 8
print(map)
}
}
}
答案 0 :(得分:0)
使用tileColumnIndex
/ tileRowIndex
获取索引时,您需要对照图块地图中的位置进行检查。在您的示例中,您将给出场景的位置,该位置可能会有所不同,具体取决于切片图的位置。
如果您在地图上使用触摸过的位置,则应该返回正确的索引。
let positionInMap = touch.location(in: map)
let column = map.tileColumnIndex(fromPosition: positionInMap)
let row = map.tileRowIndex(fromPosition: positionInMap)
示例中touchesBegan()
的更新版本
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = touches.first! as UITouch
let positionInScene = touch.location(in: self)
let touchedNode = self.atPoint(positionInScene)
if(touchedNode.name == "Tile Map Node") {
let map = touchedNode as! (SKTileMapNode)
let positionInMap = touch.location(in: map) // Get the touched position in map
print(map.tileColumnIndex(fromPosition: positionInMap))
print(map.tileRowIndex(fromPosition: positionInMap))
print(map.numberOfColumns)
print(map.numberOfRows)
print(map)
}
}
为确保在使用centerOfTile
进行定位时,光标与图块对齐,请将其作为子项添加到图块地图中,以确保它们在同一坐标系上。否则,您必须在光标位置添加必要的偏移量。
tilemap.addChild(cursor)