Giving Tile Maps a Physics Body

Layout your levels with Tile Maps then customize each tile with a physics body and whatever other custom properties you want!

Learn how to give SKTileMapNodes a physics body definition using Swift. We’ll do this by setting up an SKTileMapNode in the .sks file, then replacing the tiles with SKSpriteNodes that can have all the usual properties of an SKSpriteNode, include a physics body with Alpha channel. I’ll also point out where to put in a subclass of SKSpriteNode in case you want to get even fancier and use custom properties.

Example Code


//call this by passing in your SKTileMapNode, then you should delete the original SKTileMapNode

func giveTileMapPhysicsBody(map: SKTileMapNode )

{

 

let tileMap = map

let startingLocation:CGPoint = tileMap.position

 

let tileSize = tileMap.tileSize

 

let halfWidth = CGFloat(tileMap.numberOfColumns) / 2.0 * tileSize.width

let halfHeight = CGFloat(tileMap.numberOfRows) / 2.0 * tileSize.height

 

for col in 0..<tileMap.numberOfColumns {

 

for row in 0..<tileMap.numberOfRows {

 

if let tileDefinition = tileMap.tileDefinition(atColumn: col, row: row)

 

{

 

let tileArray = tileDefinition.textures

let tileTexture = tileArray[0]

let x = CGFloat(col) * tileSize.width – halfWidth + (tileSize.width / 2)

let y = CGFloat(row) * tileSize.height – halfHeight + (tileSize.height / 2)

 

 

let tileNode = SKSpriteNode(texture:tileTexture)

tileNode.position = CGPoint(x: x, y: y)

tileNode.physicsBody = SKPhysicsBody(texture: tileTexture, size: CGSize(width: (tileTexture.size().width ), height: (tileTexture.size().height )))

tileNode.physicsBody?.linearDamping = 60.0

tileNode.physicsBody?.affectedByGravity = false

tileNode.physicsBody?.allowsRotation = false

tileNode.physicsBody?.isDynamic = false

tileNode.physicsBody?.friction = 1

self.addChild(tileNode)

 

tileNode.position = CGPoint(x: tileNode.position.x + startingLocation.x, y: tileNode.position.y + startingLocation.y)

 

}

}

}

}

Tags: tiles, tile, tileMap, SKTileMapNode, numberOfColumns, numberOfRows, tileDefinition, userData, tileRowIndex, tileColumnIndex, physicsBody, tileArray

Download the new CartoonSmart TV App - Organize all your FREE and Premium Lessons

Get it!