我一直在努力實現一種方法來添加按鈕,並在按下場景時切換到我的第二個視圖。我已經閱讀過其他文章,但在Swift 3中已經有了ZERO運氣。我非常困惑,並且已經嘗試過但很多次都失敗了。希望你能幫助!謝謝!以編程方式將按鈕添加到GameScene.swift,並按下時轉換場景
SpriteKit中的Swift 3。
我一直在努力實現一種方法來添加按鈕,並在按下場景時切換到我的第二個視圖。我已經閱讀過其他文章,但在Swift 3中已經有了ZERO運氣。我非常困惑,並且已經嘗試過但很多次都失敗了。希望你能幫助!謝謝!以編程方式將按鈕添加到GameScene.swift,並按下時轉換場景
SpriteKit中的Swift 3。
你是什麼意思向新視圖過渡?在製作SpriteKit遊戲時,我們傾向於在SKScenes而不是視圖之間切換。所以不要試圖爲每個場景創建不同的視圖或viewControllers,只是直接在SKScenes之間切換。
關於按鈕,有很多教程可用。您基本上創建一個SKSpriteNode作爲按鈕,並在touchesBegan中查找它,並在按下按鈕時執行某些操作。
這是這裏
https://nathandemick.com/2014/09/buttons-sprite-kit-using-swift/
必要,你可以創建一個類似的按鈕子類的簡單例子。
class Button: SKNode {
let defaultButton: SKSpriteNode
let activeButton: SKSpriteNode
var action:() ->()
init(defaultButtonImage: String, activeButtonImage: String, buttonAction: @escaping() ->()) {
defaultButton = SKSpriteNode(imageNamed: defaultButtonImage)
activeButton = SKSpriteNode(imageNamed: activeButtonImage)
activeButton.isHidden = true
action = buttonAction
super.init()
isUserInteractionEnabled = true
addChild(defaultButton)
addChild(activeButton)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
activeButton.isHidden = false
defaultButton.isHidden = true
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if defaultButton.contains(location) {
activeButton.isHidden = false
defaultButton.isHidden = true
} else {
activeButton.isHidden = true
defaultButton.isHidden = false
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if defaultButton.contains(location) {
action()
}
activeButton.isHidden = true
defaultButton.isHidden = false
}
}
}
,比你的相關SKScene添加按鈕
class StartScene: SKScene {
override func didMove(to view: SKView) {
let playButton = Button(defaultButtonImage: "button", activeButtonImage: "button_active", buttonAction: loadGameScene)
playButton.position = CGPoint(x: frame.midX, y: frame.midY)
addChild(playButton)
}
func loadGameScene() {
let scene = GameScene(...)
let transition = SKTransition....
scene.scaleMode = .aspectFill
view?.presentScene(scene, transition: transition)
}
}
您還可以檢查出使用協議的其他按鈕類例如蘋果樣品遊戲DemoBots。
希望這有助於
嗨crashoverride777,請在時間,因爲我想給予好評的答案:-) –
酷添加一些代碼到你的答案,因爲鏈接可能變得不可用,我現在就去看看。謝謝你提醒我 – crashoverride777
對,做得好。 –
份額你已經嘗試什麼到目前爲止請 –