在我的游戏中,我需要使用按钮Delete!
完全删除一些节点并尝试执行此操作。我的测试节点消失了,但仍然具有大小,颜色和位置(请参见代码中的打印内容)。我找到一些以前的
关于类似主题的讨论,但无济于事。这怎么可能?我在做什么错了?
这是我的代码:
import SpriteKit
import GameplayKit
class GameScene: SKScene, ButtonDelegate {
// Basic for dynamic sizes step 01
var width = CGFloat()
var height = CGFloat()
var btnDelete = Button() // new button class
var testNode = SKSpriteNode()
override func didMove(to view: SKView) {
// Basic for dynamic sizes step 02
width = self.frame.size.width
height = self.frame.size.height
setBtnDelete()
setTestNode()
self.backgroundColor = UIColor.purple
}
func deleteNode(){
testNode.removeFromParent()
testNode.color = UIColor.cyan
print("# func deleteNode() testNode.position after delete :\(testNode.position)")
print("# func deleteNode() testNode.color after delete :\(testNode.color)")
print("# func deleteNode() testNode.size after delete :\(testNode.size)")
}
func setTestNode(){
testNode.size = CGSize(width: width*0.3, height: width*0.3)
testNode.position = CGPoint(x: width*0.5, y: height*0.5)
testNode.color = UIColor.red
self.addChild(testNode)
}
func buttonClicked(sender: Button) {
//print("# you clicked the button named \(sender.name!)")
deleteNode()
}
func setBtnDelete(){
btnDelete = Button(texture: nil, color: .orange, size: CGSize(width: width*0.2, height: width*0.1))
btnDelete.name = "btnDelete"
btnDelete.position = CGPoint(x: width*0.5, y: height*0.18)
btnDelete.delegate = self
btnDelete.zPosition = 2
addChild(btnDelete)
btnDelete.label.text = "Delete!"
print("# func setBtnDelete() btnDelete.name:\(btnDelete.name!)")
}
}
班级按钮代码:
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!
var label = SKLabelNode()
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
setLabel()
}
func setLabel() {
label.zPosition = 1
label.text = "Test"
label.fontName = "Chalkduster"
label.fontSize = 34
label.numberOfLines = 0
label.horizontalAlignmentMode = .center
label.verticalAlignmentMode = .center
label.fontColor = UIColor.darkGray
label.fontName = "Chalkduster"
self.addChild(label)
}
func btnDie() {
self.isHidden = true
self.removeFromParent()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
setScale(0.9)
self.delegate.buttonClicked(sender: self)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
setScale(1.0)
}
}
答案 0 :(得分:0)
这是更新(请参见上面的评论):
testNode应该是可选的:
var testNode:SKSpriteNode?
然后(通过删除功能)可以将其设置为nil,然后释放内存。