我创建了一个可以正常工作的SKNode类。但是,实例化后,我无法更改其.position。
按钮确实显示并正常工作,但是在编程时根本不会改变位置。我在下面包括了为按钮创建的类,还添加了实例化该类并调用节点位置的代码。
类代码:
class LButton: SKNode {
var button: SKSpriteNode
private var mask: SKSpriteNode
private var cropNode: SKCropNode
private var action: () -> Void
var isEnabled = true
init(imageNamed: String, buttonAction: @escaping () -> Void) {
button = SKSpriteNode(imageNamed: imageNamed)
button.size = CGSize(width: 50.0, height: 50.0*(24/40))
mask = SKSpriteNode(color: SKColor.black, size: button.size)
mask.alpha = 0
cropNode = SKCropNode()
cropNode.maskNode = button
cropNode.zPosition = 3
cropNode.addChild(mask)
action = buttonAction
super.init()
isUserInteractionEnabled = true
setupNodes()
addNodes()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupNodes() {
button.zPosition = 0
}
func addNodes() {
addChild(button)
addChild(cropNode)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if isEnabled {
mask.alpha = 0.5
run(SKAction.scale(by: 1.05, duration: 0.05))
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if isEnabled {
for touch in touches {
let location: CGPoint = touch.location(in: self)
if button.contains(location){
mask.alpha = 0.5
} else {
mask.alpha = 0.0
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if isEnabled {
for touch in touches {
let location: CGPoint = touch.location(in: self)
if button.contains(location) {
disable()
action()
run(SKAction.sequence([SKAction.wait(forDuration: 0.2), SKAction.run({self.enable()})]))
}
}
}
}
func disable() {
isEnabled = false
mask.alpha = 0.0
button.alpha = 0.5
}
func enable() {
isEnabled = true
mask.alpha = 0.0
button.alpha = 1.0
}
}
实例代码:
var playButtonTwo: LButton {
let revealGameScene = SKTransition.fade(withDuration: 0.5)
let goToGameScene = GameSceneTwo(size: self.size)
goToGameScene.scaleMode = SKSceneScaleMode.resizeFill
var button = LButton(imageNamed: "playButton", buttonAction: { self.view?.presentScene(goToGameScene, transition:revealGameScene)
})
button.zPosition = 5
button.position = CGPoint(x: -self.frame.width*0.3, y: self.frame.height*0.4)
return button
}
调用以更改节点位置:
playButtonTwo.position = CGPoint(x:0, y: -self.frame.height*0.4)
任何建议表示赞赏!
答案 0 :(得分:0)
我认为您不应在创建按钮的位置设置按钮的位置。而是将其放置在didMove
中var playButtonTwo: LButton {
let revealGameScene = SKTransition.fade(withDuration: 0.5)
let goToGameScene = GameSceneTwo(size: self.size)
goToGameScene.scaleMode = SKSceneScaleMode.resizeFill
var button = LButton(imageNamed: "playButton", buttonAction: { self.view?.presentScene(goToGameScene, transition:revealGameScene)
})
button.zPosition = 5
// button.position = CGPoint(x: -self.frame.width*0.3, y: self.frame.height*0.4) <- comment out his line
return button
}