我正在开发一款游戏,其中角色将由一组 4 个按钮控制,就像在旧游戏机中一样。我在 spritekit 中使用 Tile Map 来创建地图。一切正常(按下按钮时玩家正在移动,场景跟随玩家)除了我的 4 个按钮在角色移动时也会移动。直到 4 个按钮移出屏幕,我再也无法控制它了。我们如何将 4 个按钮锚定到屏幕的右下角?下面是我用来创建受控按钮的代码
func controlButton() {
button = SKNode()
moveUpButton = SKSpriteNode(imageNamed: "moveup")
moveUpButton.alpha = 1
moveUpButton.setScale(1.5)
moveUpButton.position = CGPoint(x: 400 - self.frame.size.width/2, y: 0 - self.frame.size.height/2)
moveUpButton.zPosition = 2
moveLeftButton = SKSpriteNode(imageNamed: "moveleft")
...
moveRightButton = SKSpriteNode(imageNamed: "moveright")
...
moveDownButton = SKSpriteNode(imageNamed: "movedown")
...
button.addChild(moveUpButton)
button.addChild(moveLeftButton)
button.addChild(moveRightButton)
button.addChild(moveDownButton)
self.addChild(button)
}
这是我用来创建瓷砖贴图的代码,为包含墙的瓷砖添加带有物理主体的节点:
func setUpSceneWithMap(map: SKTileMapNode) {
let tileMap = map
tileMap.setScale(1)
tileMap.position = CGPoint(x: 0 - self.frame.size.width/2, y: 0 - self.frame.size.height/2)
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 {
let tileDefinition = tileMap.tileDefinition(atColumn: col, row: row)
let isEdgeTile = tileDefinition?.userData?["isWalls"] as? Bool
if (isEdgeTile ?? false) {
let x = CGFloat(col) * tileSize.width - halfWidth
let y = CGFloat(row) * tileSize.height - halfHeight
let rect = CGRect(x: 0, y: 0, width: tileSize.width, height: tileSize.height)
let tileNode = SKShapeNode(rect: rect)
tileNode.position = CGPoint(x: x, y: y)
tileNode.physicsBody = SKPhysicsBody.init(rectangleOf: tileSize, center: CGPoint(x: tileSize.width / 2.0, y: tileSize.height / 2.0))
tileNode.physicsBody?.categoryBitMask = gamePhysics.Wall
tileNode.physicsBody?.collisionBitMask = gamePhysics.Player
tileNode.physicsBody?.contactTestBitMask = gamePhysics.Player
tileNode.physicsBody?.isDynamic = false
tileMap.addChild(tileNode)
}
}
}
}
下面也是我将地图添加到场景的代码:
func createScene() {
self.physicsWorld.contactDelegate = self
for node in self.children {
if (node is SKTileMapNode){
if let theMap:SKTileMapNode = node as? SKTileMapNode {
setUpSceneWithMap(map: theMap)
}
}
}
createPlayer()
createCamera()
}