2015-09-03 83 views
2

我有一款適用於iPad的遊戲,其中兩個不同的玩家可以同時與環境進行交互。當同一臺設備上的兩個人同時玩遊戲時,我有一個問題,我不知道如何解決。我希望遊戲的行爲方式如下:當玩家觸摸一個精靈,並在另一個精靈中完成觸摸時,該應用必須能夠知道它已經是同一個玩家。不知道如何處理觸摸作爲單個實體

我的應用程序現在的功能如下:假設player1觸及一個精靈。然後,player2觸及另一個。他們都沒有完成這個接觸。現在,player1在第三個精靈中結束他的觸摸。但是,對於我現在使用的代碼,它需要做的是在第二個和第三個sprite中調用函數「action」,當我需要傳遞第一個和第三個sprite時,我嚇壞了很少,因爲我不知道該怎麼做。這裏有您需要的代碼:

var globalReference: Int = 0 

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    let touch: UITouch! = touches.first as UITouch! 
    let touchLocation = touch.locationInNode(self) 
    var spriteTouched: Int? = 0 

    if self.nodeAtPoint(touchLocation).name != nil { 
     spriteTouched = Int(self.nodeAtPoint(touchLocation).name!) 
     globalReference = spriteTouched 
    } 
} 

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    let touch: UITouch! = touches.first as UITouch! 
    let touchLocation = touch.locationInNode(self) 
    var spriteTouched: Int? = 0 
    if self.nodeAtPoint(touchLocation).name != nil { 
     spriteTouched = Int(self.nodeAtPoint(touchLocation).name!){ 
     if(globalReference != spriteTouched) { 
      action1(globalReference, spriteTouched) 
     } else { 
      action2(globalReference) 
      } 
     } 
    } 
} 

我瞭解什麼是精靈使用「名稱」裏的名字始終是一個Int觸摸的方式。我使用變量globalReference來了解touchesBegin在touchesEnded中觸摸了什麼樣的sprite,以及這個實現是我真的不知道如何解決的。考慮一些罕見的情況,比如當你不接觸解決的精靈時。 如果有人能幫我一點點,我將不勝感激...

謝謝!

PS:是的,我知道這是一個很難回答的問題......只是一個挑戰:)

+0

如果PLAYER1倒是一個精靈,然後player2觸及不同的精靈,我假設你的應用程序是延遲檢測。現在,如果player1觸及第三個精靈,那麼您的應用程序將如何知道該玩家1是做出觸摸的玩家?如果你的應用知道誰觸摸了什麼,那麼它應該知道誰停止觸摸什麼。 –

+0

也許我沒有正確解釋。第一個精靈沒有第一個觸摸,第三個精靈沒有第一個觸摸,一切都只是一個觸摸,但它有一個開始(第一個精靈)和結束(第三個精靈)。我想要的是整個觸摸已經開始在一個精靈(第一個),並在另一個(第三個)結束。 – Adri

回答

1

UITouch對象是持久的。保持對觸摸中發現的精靈名稱的引用。

類屬性:

var touchesToSprites = [UITouch:Int]() 
中的touchesBegan

touchesToSprites[touch] = spriteTouched 
在touchesEnded

action1(touchesToSprites[touch], spriteTouched) 
// remove touchesToSprites[touch] when done 
+0

哇...它看起來可能會有效。謝謝!當我嘗試它時,只要它有效,我會將此答案標記爲正確的答案。 – Adri

+0

像魔術一樣工作。謝謝親愛的先生。 – Adri