有没有一种方法可以将操作添加到除swift之外的一个节点的所有创建的节点?

问题描述:

我想为场景中除一个或两个节点以外的所有节点添加一个动作。有没有一种方法可以将操作添加到除swift之外的一个节点的所有创建的节点?

或者,我想找到一种方法来使用“名称”方法以不同方式访问所有节点。

这不是完整的游戏,但我不想使用“名称”方法,因为每个方块都有不同的名称。

import SpriteKit 
import GameplayKit 
var Score = 0 

class GameScene: SKScene { 

let SquareSide = 100 
var touchedNode = SKNode() 
var touchLocation = CGPoint() 
let ScoreLabel = SKLabelNode() 
let squareNumber = 0 

override func didMove(to view: SKView) { 
CreatSquares() 
} 

func CreatSquares(){ 

let square = SKShapeNode(rect: CGRect(x:  Int(arc4random_uniform(UInt32(self.frame.width))), y: Int(arc4random_uniform(UInt32(self.frame.height))), width: SquareSide, height: SquareSide)) 

if Score <= 10{ 
square.fillColor = UIColor.orange} 
else{ 
square.fillColor = UIColor.blue 
     } 
square.physicsBody =  SKPhysicsBody(rectangleOf: CGSize(width: square.frame.width, height: square.frame.height), center: CGPoint(x: square.position.x, y: square.position.y)) 

square.physicsBody?.affectedByGravity = false 

square.physicsBody?.allowsRotation = false 
square.physicsBody?.categoryBitMask = 0 
square.name = "square\(number)" 

number++ 
self.addChild(square) 

    } 


} 
func CreatScoreLabel(){ 
let ScoreLabel = SKLabelNode() 

ScoreLabel.text = "Your Score is:\(Score)" 

ScoreLabel.position = CGPoint(x: self.frame.width/2, y: self.frame.height - 50) 

ScoreLabel.color = UIColor.white 
    self.addChild(ScoreLabel) 

} 

func updatScore(){ 
ScoreLabel.text = "Your Score is:\(Score)" 

} 

override func touchesBegan(_ touches:  Set<UITouch>, with event: UIEvent?) { 
for touch in touches { 
touchLocation = touch.location(in: self) 
touchedNode = self.atPoint(touchLocation) 
if touchedNode.name == "square"{ 
Score += 1 
touchedNode.removeFromParent() 
      } 


    } 

    } 
override func update(_ currentTime: TimeInterval) { 
updatScore() 
} 
+0

我发现你的问题不清楚,请你解释一下,但更多,我可以帮忙吗? –

+0

我想为场景中除了一个节点(比如LabelNode)上的所有创建的节点添加动作 – Nour

+0

但是现在在我的代码中,我只有一个节点,我不想为它添加动作,但是当我想在不止一个节点上完成我的游戏。不想为他们添加动作。 – Nour

正如Confused解释乱搞通过你的节点层次更快,更容易,我认为你忘了enumerateChildNodes(withName:

实权实际上,这个名字:

要搜索的名称。这可能是 节点的文字名称或自定义搜索字符串。见Searching the Node Tree

这意味着,你也可以这样做:

self.enumerateChildNodes(withName: "//square*") { node, _ in 
    // node is equal to each child where the name start with "square" 
    // in other words, here you can see square0, square1, square2, square3 etc... 
    if node.name == "square3" { 
     // do whatever you want with square3 
    } 
} 

//指定搜索应在根节点开始并在整个节点树递归执行。否则,它会从当前位置执行递归搜索。

*表示搜索匹配零个或多个字符。

要做到这一点,最简单的方法是将所有你想要的操作添加到节点添加到一个数组,然后遍历数组,添加动作,当你想/需要。

如果您的物体非常庞大而且复杂,这会造成记忆打击,但它是最有组织和最快速的方式,无需使用.name

而且远远比enumerateChildNodes...