所以基本上我有一个名为tree的节点,我在.sks文件中设计它。
我为skspritenode添加了一个自定义类,但自定义类似乎不会影响节点。
我正在尝试检测节点及其子节点上的触摸。
使用removefromparent()
和addchild()
函数将此节点转移到多个场景,因此不是在每个场景上编写重复代码来检测触摸,而是尝试使用自定义节点类来执行此操作。 ..任何帮助将不胜感激。
注意我必须使用带有纹理的super.init函数,但我想使用已在场景中创建的节点。
我的班级代码
import SpriteKit
class tree: SKSpriteNode {
init() {
let texture = SKTexture(imageNamed: "tree")
super.init(texture: texture, color: SKColor.clear, size: texture.size())
self.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
print("touched!")
}
}
}
答案 0 :(得分:2)
在this回答中有一个很好的解释,应该清楚你对 SKS 文件和子类化的看法。
关于你的代码,使用大写字母作为类名是一个好习惯,在你的情况下,我更喜欢使用class Tree
而不是类树。
关于第二个问题,您可以使用userData将对象从一个场景转移到另一个场景,如下例所示:
import SpriteKit
class GameScene: SKScene {
private var label : SKLabelNode?
var tree : Tree!
override func didMove(to view: SKView) {
self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
if let label = self.label {
label.alpha = 0.0
label.run(SKAction.fadeIn(withDuration: 2.0))
}
self.isUserInteractionEnabled = true
tree = Tree()
tree.name = "tree"
addChild(tree)
tree.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
let pointOfTouch = touch.location(in: self)
let nodeUserTapped = atPoint(pointOfTouch)
if nodeUserTapped.name == "tree" {
tree.removeFromParent()
let sceneToMoveTo = Scene2.init(size: self.size)
sceneToMoveTo.userData = NSMutableDictionary()
sceneToMoveTo.userData?.setObject(tree, forKey: "tree" as NSCopying)
let gameTransition = SKTransition.fade(withDuration: 0.5)
self.view!.presentScene(sceneToMoveTo, transition: gameTransition)
}
}
}
}
class Scene2: SKScene {
var tree:Tree!
override func didMove(to view: SKView) {
print("This is the scene: \(type(of:self))")
guard let previousValue = self.userData?.value(forKey: "tree") else { return }
if previousValue is Tree {
tree = previousValue as! Tree
addChild(tree)
tree.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
let pointOfTouch = touch.location(in: self)
let nodeUserTapped = atPoint(pointOfTouch)
if nodeUserTapped.name == "tree" {
tree.removeFromParent()
if let sceneToMoveTo = SKScene(fileNamed: "GameScene") {
sceneToMoveTo.scaleMode = .aspectFill
sceneToMoveTo.userData = NSMutableDictionary()
sceneToMoveTo.userData?.setObject(tree, forKey: "tree" as NSCopying)
let gameTransition = SKTransition.fade(withDuration: 0.5)
self.view!.presentScene(sceneToMoveTo, transition: gameTransition)
}
}
}
}
}
正如您可以阅读我在父类和节点中对触摸的控制,可以通过将自定义touchesBegan
的{{1}}方法更改为:
SKSpriteNode
请记住,如果要使用它们,还应将此方法扩展到其他触摸方法。