Adding physics bodies to all tiles on an SKTileMapNode

62 views Asked by At

I'm trying to make a simple game in the latest version of Xcode. I use a TileMap that is pretty simple. I'm trying to figure out how to add a physics body to each and every tile. I'm stuck at getting the position of each tile and adding an SKNode there. Any way at getting the position of each tile would be extremely helpful. All the code below is in didMove(to: view)

let tileSize = grassTileMap.tileSize
let halfWidth = CGFloat(grassTileMap.numberOfColumns) / 2.0 * tileSize.width
let halfHeight = CGFloat(grassTileMap.numberOfRows) / 2.0 * tileSize.height

for node in self.children {
    if node.name == "grassTileMap" {
        grassTileMap = node as! SKTileMapNode
    }
    
    for col in 0..<grassTileMap.numberOfColumns {
        for row in 0..<grassTileMap.numberOfRows {
            let tileDef = grassTileMap.tileDefinition(atColumn: col, row: row)
            if tileDef == nil {
                print("no tile here")
            } else {
                
                let hitboxTileNode = SKSpriteNode(color: UIColor.clear, size: CGSize(width: 35.5, height: 35.5))
                
                // I need to set the position of each tile to hitBoxTileNode here
                
                hitboxTileNode.anchorPoint = CGPoint(x: 0, y: 0)
                hitboxTileNode.physicsBody = SKPhysicsBody(edgeLoopFrom: hitboxTileNode.frame)
                hitboxTileNode.physicsBody?.affectedByGravity = false
                hitboxTileNode.physicsBody?.isDynamic = false
                hitboxTileNode.physicsBody?.pinned = false
                hitboxTileNode.physicsBody?.restitution = 0
                hitboxTileNode.physicsBody?.friction = 0
                addChild(hitboxTileNode)
            }
        }
    }
}
0

There are 0 answers