如何在通用应用程序中每个设备的角落放置硬币标签?



我想创建一个位于每个设备左上角的SKLabelNode。另外,在左上角标签的左侧,我想要一张硬币图像,以显示这是当前的硬币计数标签。 每次我把标签放在iPhone 6s+的角落里时,它都不在我的iPad的角落里。

这是我到目前为止的代码:

cornerCoin.position = CGPoint(x: screenWidth / -3.1, y: screenHeight / 3.175)
cornerCoin.zPosition = 10
cameraNode.addChild(cornerCoin)
coinLabel.position = CGPoint(x: screenWidth / -2.4, y: screenHeight / 8)
coinLabel.zPosition = 1
coinLabel.fontSize = 50
coinLabel.fontColor = UIColor.black
coinLabel.fontName = "04b19"
cameraNode.addChild(coinLabel)

就个人而言,我不会跟踪screenWidth/screenHeight,它从一开始就违背了SpriteKit的基础(你的场景表现为你的虚拟屏幕,这就是你应该如何处理里面的一切(相反,你应该做的是从屏幕转换为场景,这样无论缩放模式或锚点如何,你的标签都是你想要的位置。

要将视图的右上角转换为场景,请执行

if let view = scene.view
{
let topRightPos = view.convert(CGPoint(x:view.frame.maxX,y:view.frame.minY),to:scene)
let camTopRight = scene.convert(topRightPos,to:cameraNode)
}

现在我们知道我们的右上角位置了:

我们可以做到

if let view = scene.view
{
let topRightPos = view.convert(CGPoint(x:view.frame.maxX,y:view.frame.minY),to:scene)
let camTopRight = scene.convert(topRightPos,to:cameraNode)
coinLabel.position = camTopRight
coinLabel.zPosition = 1
coinLabel.fontSize = 50
coinLabel.fontColor = UIColor.black
coinLabel.fontName = "04b19"
coinLabel.horizontalAlighmentMode = .right
coinLabel.verticalAlighmentMode = .top        
cameraNode.addChild(coinLabel)
}

向右对齐我们的标签,使文本始终向左延伸,然后添加硬币,我们这样做:

if let view = scene.view
{
let topRightPos = view.convert(CGPoint(x:view.frame.maxX,y:view.frame.minY),to:scene)
let camTopRight = scene.convert(topRightPos,to:cameraNode)
coinLabel.position = camTopRight
coinLabel.zPosition = 1
coinLabel.fontSize = 50
coinLabel.fontColor = UIColor.black
coinLabel.fontName = "04b19"
coinLabel.horizontalAlighmentMode = .right
coinLabel.verticalAlighmentMode = .top        
cameraNode.addChild(coinLabel)
cornerCoin.position = CGGPoint(x:0.0,y:coinLabel.frame.midY)
cornerCoin.anchorPoint = CGPoint(x:1.0,y:0.5)
cornerCoin.zPosition = 10
cameraNode.addChild(cornerCoin)
}

我们的标签现在应该位于相机的右上角,硬币应该在标签的左侧,与文本垂直居中。

如果您不喜欢顶部对齐的外观,您可能希望尝试标签的位置。

最新更新