2015-11-03 101 views
1

每次單擊屏幕時,我都會創建一個圓形的新SKShapeNode。處理SpriteKit中的每個節點Swift

我試圖做下一件事:每當新的SKShapeNode在地面下(地面y是屏幕的一半) - 他變綠了。 所以我試過這個:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
newestBall = SKShapeNode(circleOfRadius: 10) 
     newestBall.physicsBody = SKPhysicsBody(circleOfRadius: newestBall.frame.height/2) 
     newestBall.position = CGPoint(x: CGRectGetMidX(self.frame) ,y: self.frame.size.height - newBall.frame.height) 
     newestBall.fillColor = SKColor.blueColor() 
     newestBall.strokeColor = SKColor.blackColor() 
     newestBall.glowWidth = 1.0 
     newestBall.zPosition = 9 
     newestBall.physicsBody?.dynamic = true 
     newestBall.physicsBody?.allowsRotation = false 
     newestBall.physicsBody?.friction = 0 
     newestBall.physicsBody?.restitution = 1 
     newestBall.physicsBody?.linearDamping = 0 
     newestBall.physicsBody?.angularDamping = 0 
     newestBall.physicsBody?.categoryBitMask = ballsGroup 
} 
override func update(currentTime: CFTimeInterval) { 
if newestBall.position.y < ground.position.y { 
      newestBall.fillColor = SKColor.greenColor() 
     } 
} 

它的工作原理!但是,當我點擊兩次並創建2個球(並且第一個球仍然沒有在地下)時,只有最後一個球變成綠色,因爲他是newestBall

我想讓每個球都是綠色的,如果他在地下。

回答

2

給您newestBall一個名字:

newestBall.name = "Ball" 

然後用名字= 「球」 和變色IR要求檢查throught所有節點AR滿足

self.enumerateChildNodesWithName("Ball", usingBlock: { 
     (node: SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Void in 
     let shapeNode = node as! SKShapeNode 
     if shapeNode < self.ground.position.y { 

      shapeNode = SKColor.greenColor() 
     } 
    }) 

您可以添加到update()selfparentNode或您最新的球和地面節點。

+0

它給了我這個錯誤: '(SKShapeNode!,UnsafeMutablePointer ) - > Void'不能轉換爲'(SKNode,UnsafeMutablePointer ) - > Void'。當我嘗試將'SKShakenode'改爲'SKNode'時,它在'node = SKColor.greenColor()'行給了我另一個錯誤:無法將'UIColor'類型的值賦值爲'SKNode!'類型的值。 – Eliko

+0

@Eliko檢查我的編輯。 – Darvydas

+0

正確!謝謝!在'shapeNode = SKColor.greenColor()'行後面加上}來關閉if語句。並添加.fillColor這行代碼:'shapeNode = SKColor.greenColor()' – Eliko

相關問題