2017-07-25 40 views
-1

我正面臨以下問題。SKShapeNode在函數中定義...如何獲得標識符

func createButton(bx: CGFloat, by: CGFloat, bw: CGFloat, bh: CGFloat, yourText: String) { 

let button = SKShapeNode(rect: CGRect(x: bx, y: by, width: bw, height: bh), cornerRadius: 5) 
button.fillColor = UIColor.blue 
(...) 
self.addChild(button) 

我打電話這樣的功能:

我爲了使用SpriteKit產生自定義按鈕創建一個功能

self.createButton(bx: CGFloat(200), by: CGFloat(0), bw: CGFloat(130), bh: CGFloat(30), yourText: "testlabel") 

我怎麼可以參考這個創建的對象後面?

EG:

我試圖改變使用觸摸單獨創建的元素的位置...

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    if let touch = touches.first { 
     let touchLoc = touch.location(in: self) 
     let touchWhere = nodes(at: touchLoc) 

     if !touchWhere.isEmpty { 
      for node in touchWhere { 
       if let node = node as? SKShapeNode { 
        if node == element1 { 
       } 

在早期階段,我會創造這樣

element1 = SKShapeNode(rect: CGRect(x: 100, y: 100, width: 30, height: 30), cornerRadius: 10) 
    element1.fillColor = UIColor.red 
     addChild(element1) 
的SkSpriteNode

在上面的例子中,我能夠通過調用標識符「element1」來引用這個特定元素,它說

if node == element1 { 

但我怎麼能實現同樣的事情時使用的功能中創建多個元素...

最後,我想每個元素單獨使用觸摸

移動?

回答

0

您已經在發佈的touchesBegan示例中找到了您的節點。如果您在創建按鈕時指定了name,則可以使用它來確切確定用戶觸摸了哪個SKShapeNode並相應採取相應措施。

E.g. button.name = yourText

然後在touchedBegan,您可以查看哪個按鈕被觸動:

if node.name = "testlabel" { 
... 
} 

你也子SKShapeNode創建您的專業按鈕。

+0

感謝您的快速反應! 但我怎麼能真正分配一個名稱的元素,通過一個函數創建。 這是確切我的問題... – mtacki

+0

當這個按鈕被觸摸時,你想要發生什麼?如果你已經使用這個功能創建了多個相同的按鈕,他們都應該被觸摸或不同的事情做同樣的事情?如果不同,用戶如何知道按哪個按鈕?不同按鈕的顯着特點是什麼? –

+0

@mtacki請參閱我的編輯以查看我的答案,以瞭解如何使用'name'屬性。 –

0

試圖創建類,其中包含的功能...

class Arzt { 


    func createButton(bx: CGFloat, by: CGFloat, bw: CGFloat, bh: CGFloat, yourText: String) { 

     let button = SKShapeNode(rect: CGRect(x: bx, y: by, width: bw, height: bh), cornerRadius: 5) 

     button.fillColor = UIColor.darkGray 

     let label = SKLabelNode(fontNamed:"ArialMT") 
     label.text = yourText 

     button.addChild(label) 
     self.addChild(button) 

} 
} 

我現在可以創建Arzt的新實例,說

let test = Arzt() 
test.createButton(bx: CGFloat(200), by: CGFloat(150), bw: CGFloat(130), bh: CGFloat(30), yourText: "text") 

我想通過這樣做,我以後可以通過他們的名字訪問單個實例,在這種情況下「測試」

這裏還有一些錯誤... 它扔掉了

類型「GameScene的值。Arzt」對在函數的最後一行沒有成員‘的addChild’

self.addChild(button) 
0

我想你一定看過一些教程之前在這裏問一個問題...

添加一個字符串類似的參考

func createButton(bx: CGFloat, by: CGFloat, bw: CGFloat, bh: CGFloat, yourText: String, ref: String) { 

    let button = SKShapeNode(rect: CGRect(x: bx, y: by, width: bw, height: bh), cornerRadius: 5) 
    button.fillColor = UIColor.blue 
    button.name = ref //here you can reference it 
    (...) 
    self.addChild(button) 
    ..... 
} 

if !touchWhere.isEmpty { 
      for node in touchWhere { 
       if let node = node as? SKShapeNode { 
        switch node.name 
         case "ref1" 
          .... 
         case "ref2" 
          .... 
       } 
+0

非常感謝! 我正在閱讀教程 - 但它是如此令人興奮的嘗試的東西... 我知道,我必須學習很多 - 仍然有趣潛入一些先進的東西:-) 反正 - 謝謝一堆! – mtacki