我有一个代码来为 tilemap 中的每个瓦片定义 PhysicsBody,如下所示:
func setUpSceneWithMap(map: SKTileMapNode) {
let tileMap = map
tileMap.setScale(0.4)
let startingLocation: CGPoint = tileMap.position
let tileSize = tileMap.tileSize
let halfWidth = CGFloat(tileMap.numberOfColumns) / 2.0 * tileSize.width * 0.4
let halfHeight = CGFloat(tileMap.numberOfRows) / 2.0 * tileSize.height * 0.4
for col in 0..<tileMap.numberOfColumns {
for row in 0..<tileMap.numberOfRows {
if tileMap.tileDefinition(atColumn: col, row: row) != nil {
// defining different types of tile
let tileDefinition = tileMap.tileDefinition(atColumn: col, row: row)
...
let isTrapTile = tileDefinition?.userData?["isTraps"] as? Bool
let x = CGFloat(col) * (tileSize.width) * 0.4 - halfWidth
let y = CGFloat(row) * (tileSize.height) * 0.4 - halfHeight
let rect = CGRect(x: 0, y: 0, width: tileSize.width * 0.4 , height: tileSize.height * 0.4)
let tileNode = SKShapeNode(rect: rect)
tileNode.position = CGPoint(x: x + startingLocation.x, y: y + startingLocation.y)
tileNode.zPosition = 1
tileNode.physicsBody = SKPhysicsBody(edgeLoopFrom: rect)
// Create the 4 checkpoint-tiles at the center of the maze
...
// Create the wall tile
...
// Create the trap tile
if (isTrapTile ?? false) {
tileNode.physicsBody?.categoryBitMask = gamePhysics.Trap
tileNode.physicsBody?.collisionBitMask = 0
tileNode.physicsBody?.contactTestBitMask = gamePhysics.Player
tileNode.physicsBody?.isDynamic = false
}
self.addChild(tileNode)
}
}
}
}
我的瓦片地图中有 3 种不同的瓦片集:墙、检查点和陷阱。使用上面的代码,我已经为它们分配了一个带有物理体的 Spritenode。现在,我希望我的陷阱图块不可见,这样玩家就看不到它。实现它的最有效方法是什么?