作者:黄宗翰琼琦莉雯 | 来源:互联网 | 2023-02-01 19:41
我正在为我正在构建的精灵工具包应用程序创建主菜单.在整个项目中,我使用SKScenes来保持我的关卡和实际的游戏玩法.但是,现在我需要一个主菜单,其中包含"Play","Levels","Shop"等按钮......但是,我现在添加按钮的方式感觉不太舒服,就像这样:
let currentButton = SKSpriteNode(imageNamed: button) // Create the SKSpriteNode that holds the button
self.addChild(currentButton) // Add that SKSpriteNode to the SKScene
我检查按钮的触摸如下:
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
let touch = touches.first
let touchLocation = touch!.location(in: self)
for node in self.nodes(at: touchLocation) {
guard let nodeName = node.name else {
continue
}
if nodeName == ButtonLabel.Play.rawValue {
DispatchQueue.main.asyncAfter(deadline: .now()) {
let transition = SKTransition.reveal(with: .left, duration: 1)
self.view?.presentScene(self.initialLevel, transition: transition)
self.initialLevel.loadStartingLevel()
}
return
}
if nodeName == ButtonLabel.Levels.rawValue {
slideOut()
}
}
}
但是,我不知道这是否有效.我正在考虑使用UIButtons,但为此我必须使用UIView?
或者我可以将UIButtons添加到SKView (我真的没有区分SKView,SKScene和UIView)菜单推荐什么?
1> Ron Myschuk..:
我完全赞同@Whirlwind,为你的按钮创建一个单独的类来处理你的工作.我不认为@ElTomato的建议是正确的建议.如果您创建一个包含按钮的图像,则您对这些按钮的放置,大小,外观和按钮状态没有灵活性.
这是一个非常简单的按钮类,它是SKSpriteNode的子类.它使用委托将信息发送回父节点(例如已按下哪个按钮),并为您提供简单的状态更改(单击时变小,发布时恢复正常大小)
import Foundation
import SpriteKit
protocol ButtonDelegate: class {
func buttonClicked(sender: Button)
}
class Button: SKSpriteNode {
//weak so that you don't create a strong circular reference with the parent
weak var delegate: ButtonDelegate!
override init(texture: SKTexture?, color: SKColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
isUserInteractiOnEnabled= true
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
setScale(0.9)
self.delegate.buttonClicked(sender: self)
}
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
setScale(1.0)
}
}
此按钮可以通过2种方式实例化.您可以在场景编辑器中创建它的实例,或在代码中创建实例.
class MenuScene: SKScene, ButtonDelegate {
private var button = Button()
override func didMove(to view: SKView) {
if let button = self.childNode(withName: "button") as? Button {
self.button = button
button.delegate = self
}
let button2 = Button(texture: nil, color: .magenta, size: CGSize(width: 200, height: 100))
button2.name = "button2"
button2.position = CGPoint(x: 0, y: 300)
button2.delegate = self
addChild(button2)
}
}
func buttonClicked(sender: Button) {
print("you clicked the button named \(sender.name!)")
}
您必须记住使场景符合委托
class MenuScene: SKScene, ButtonDelegate
func buttonClicked(sender: Button) {
print("you clicked the button named \(sender.name!)")
}