我体验过将 UIButtons 和 UILabels 添加到 SpriteKit 场景中,这对于定位它们的问题会变得非常技术性。由于 UI 对象位于视图上,而不是直接位于 SpriteKit 场景上。您可以将 SKSpriteNode 用作按钮,将 SKLabelNode 用作标题,用于菜单场景。
Sprite 套件场景放置在 UIView 上,并根据您定义的缩放模式进行缩放。 Apple 的默认缩放模式 .aspectFill 不需要调整 Sprite 套件对象在不同手机设备屏幕尺寸上的定位。
这是一个 SKSpriteNode 的自定义类,具有与按钮相同的功能。
import Foundation
import SpriteKit
class ButtonLabelNode : SKSpriteNode {
let buttonPressed: () -> ()
init(texture: SKTexture?, color: UIColor, size: CGSize, text: String, buttonPressed: @escaping () -> ()) {
self.buttonPressed = buttonPressed
super.init(texture: texture, color: color, size: size)
let label = SKLabelNode(fontNamed: "Futura")
label.fontSize = 50
label.fontColor = SKColor.red
label.position = CGPoint.init(x: 0.0, y: 0.0)
label.zPosition = 1
label.verticalAlignmentMode = .center
label.text = text
self.addChild(label)
self.isUserInteractionEnabled = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.alpha = 0.8
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.alpha = 1.0
buttonPressed()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
当在 SpriteNode 上开始触摸时,alpha 减小到 0.8,并在触摸结束时回到 1.0,给它与 UIButton 相同的视觉效果。在覆盖的函数“touchesEnded”中,有一个函数在每次按下按钮时都会被调用,该函数被添加到初始化程序中,并且可以在你的游戏场景中进行初始化。
override func didMove(to view: SKView) {
let labelNode = LabelNode(texture: nil, color: .white, size: CGSize.init(width: 200, height: 100), text: "Play", buttonPressed: playButton)
labelNode.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
self.addChild(labelNode)
}
func playButton()
{
print("play")
}
您可以创建任意数量的此类实例,并赋予它们自己的功能,因为添加的初始化函数对其自己的实例是唯一的。与为类提供所需的协议方法不同,因为这将影响类的所有实例。