Swift 中事件的 SpriteKit 按钮

SpriteKit button with events in Swift

我正在尝试在 Sprite Kit 上为游戏制作一个按钮,但仅使用 Swift 代码。 我需要“touchUpInside”事件行为。我已经搜索过了,但没有找到任何有用的东西。

我已经尝试了一些方法,但我想知道最好的实施方法是什么?我不想使用 UITouchRecognizer,因为我认为在只有一个 SKView 的游戏环境中是错误的,对吗?

是touch out结束的时候,我理解这就像tochUpInside

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { }

不要忘记启用与用户的互动yourBtn.userInteractionEnabled = true

我建立了一个example to do a Simple Button with SpriteKit

对于 SpriteKit 中基于触摸事件的节点,您需要子class SKSpriteNode 并在那里处理触摸。

AGSpriteButton已经完成了这样的实现。它是用Objective-C写的,但你应该能很容易地理解它。

A​​GSpriteButton 也可以与 Swift 一起使用。您只需要在 bridging header.

中导入 class
let button = AGSpriteButton(color: UIColor.greenColor(), andSize: CGSize(width: 200, height: 60))
button.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)

//Event-based selector as in UIButton
button.addTarget(self, selector: "addSpaceship", withObject: nil, forControlEvent:AGButtonControlEvent.TouchUpInside)

button.setLabelWithText("Spaceship", andFont: nil, withColor: UIColor.blackColor())
addChild(button)

我认为你是对的,不应该使用 UITouchRecognizers,男子气概,因为你必须将它添加到 SKView 并在按钮离开屏幕时将其删除。

如果你想构建一个通用的按钮或开关,你应该试试我做的这个控件,使用起来非常简单: 你只需初始化你想要的 Button/Switch 类型(ColoredSprite、Textured 或 TextOnly)

let control = TWButton(normalColor: SKColor.blueColor(), highlightedColor: SKColor.redColor(), size: CGSize(width: 160, height: 80))

并且在初始化之后你添加一个闭包(就像 UIButton 上的 addTargetForSelector)

 control.addClosureFor(.TouchUpInside, target: self, closure: { (scene, sender) -> () in
            scene.testProperty = "Changed Property"
        })
    }

就是这样!在 GitHub 页面的自述文件部分有更多信息:https://github.com/txaidw/TWControls

但是如果你想在特定节点中实现,我是这样做的:

internal override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    let touch = touches.first as! UITouch
    let touchPoint = touch.locationInNode(self.parent)

    if self.containsPoint(touchPoint) {
        self.touchLocationLast = touchPoint
        touchDown()
    }
}

internal override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    let touch = touches.first as! UITouch
    let touchPoint = touch.locationInNode(self.parent)
    self.touchLocationLast = touchPoint
}


internal override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    let touch = touches.first as! UITouch
    let touchPoint = touch.locationInNode(self.parent)

        if let lastPoint = self.touchLocationLast where self.containsPoint(lastPoint) {
            // Ended inside
            touchUpInside()
        }
        else {
            // Ended outside
            touchUpOutside()
        }
}