2016-12-13 16 views
3

我想爲場景中除一個或兩個節點以外的所有節點添加一個動作。有沒有一種方法可以將操作添加到除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

回答

1

正如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 
    } 
} 

//指定搜索應在根節點開始並在整個節點樹遞歸執行。否則,它會從當前位置執行遞歸搜索。

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

1

要做到這一點,最簡單的方法是將所有你想要的操作添加到節點添加到一個數組,然後遍歷數組,添加動作,當你想/需要。

如果您的物體非常龐大而且複雜,這會造成記憶打擊,但它是最有組織和最快速的方式,無需使用.name

而且遠遠比enumerateChildNodes...

相關問題