如何在精灵套件游戏中添加普通按钮?



所以到目前为止我已经制作了 2 款游戏,我总是使用 touchesBegin 函数和 SpriteNode 创建一个菜单,就像这样:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if (atPoint(location).name == "playButton"){
startGame()
}
}
}

但是这种方式非常丑陋,因为只要您触摸按钮,它就会调用相应的操作,并且您无法取消它。但是对于普通的UIButton,它只会在您将手指从按钮上移开后调用操作,您甚至可以通过将手指从按钮上移开来单击按钮。问题是,我不知道如何将 UIButton 添加到我的 MenuScene.swift 文件中,而且我也不使用故事板,因为它只是让我感到困惑,我不明白 .sks、.swift 和 .故事板文件链接在一起,这对我来说毫无意义。我的意思是.sks和.storyboard文件都是用于构建GUI的,但是在.sks中,您无法添加UIButton...但是为什么???有什么方便的方法来添加按钮吗?

我不会在我的 Spritekit 代码中使用 UIButton,你最好在 Spritekit 中创建自己的 Button 类并使用它。sks文件没有链接到故事板,它链接到你指定的任何类(GameScene,MenuScene),它甚至可以链接到具有自己类的较小对象(ScoreHUD,Castle等)。

老实说,你只是想过按钮的事情。想想触摸事件。触摸如果希望对象在手指向上调用触摸时触发,请单击对象时开始触发已结束

这是我为这个例子写的一个非常简单的按钮类,你可以用它做很多事情,但这涵盖了基础知识。它决定按钮是向下还是向上单击,并且如果您将手指移开按钮,则不会单击。它使用协议将点击事件传递回父级(可能是你的场景)

您还可以通过将 colorSprite/或图像拖到场景编辑器上并在自定义类检查器中使其成为"按钮"的自定义类来将其添加到 sks 文件中。 按钮类...

protocol ButtonDelegate: class {
func buttonClicked(button: Button)
}
class Button: SKSpriteNode {
enum TouchType: Int {
class down, up
}
weak var buttonDelegate: ButtonDelegate!
private var type: TouchType = .down 
init(texture: SKTexture, type: TouchType) {
var size = texture.size()
super.init(texture: texture ,color: .clear, size: size)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
isPressed = true
if type == .down {
self.buttonDelegate.buttonClicked(button: self)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first as UITouch! {
let touchLocation = touch.location(in: parent!)
if !frame.contains(touchLocation) {
isPressed = false
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard isPressed else { return }
if type == .up {
self.buttonDelegate.buttonClicked(button: self)
}
isPressed = false
}
}

在您的游戏场景文件中

class GameScene: SKScene, Button {
private var someButton: Button!
private var anotherButton: Button!
func createButtons() {
someButton = Button(texture: SKTexture(imageNamed: "blueButton"), type: .down)
someButton.position = CGPoint(x: 100, y: 100)
someButton.Position = 1
someButton.name = "blueButton"
addChild(someButton)
anotherButton = Button(texture: SKTexture(imageNamed: "redButton"), type: .up)
anotherButton = CGPoint(x: 300, y: 100)
anotherButton = 1
anotherButton = "redButton"
addChild(anotherButton)
}
func buttonClicked(button: Button) {
print("button clicked named (button.name!)")
}
}

最新更新