2017-04-08 58 views
0

今天我的編碼遇到了一些麻煩。試圖製作一個「自動」武器,但無法讓選擇器正常工作。 下面是代碼在xcode中使用選擇器swift

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 

    for touch in (touches){ 
     let location = touch.location(in: self)func spawnBullets(){ 
       let Bullet = SKSpriteNode(imageNamed: "circle") 
       Bullet.zPosition = -1 
       Bullet.position = CGPoint(x: ship.position.x,y: ship.position.y) 
       Bullet.size = CGSize(width: 30, height: 30) 

       Bullet.physicsBody = SKPhysicsBody(circleOfRadius: 15) 
       Bullet.physicsBody?.categoryBitMask = PhysicsCategory.Bullet 

       Bullet.name = "Bullet" 
       Bullet.physicsBody?.isDynamic = true 
       Bullet.physicsBody?.affectedByGravity = false 
       self.addChild(Bullet) 

       var dx = CGFloat(location.x - base2.position.x) 
       var dy = CGFloat(location.y - base2.position.y) 

       let magnitude = sqrt(dx * dx + dy * dy) 

       dx /= magnitude 
       dy /= magnitude 

       let vector = CGVector(dx: 30.0 * dx, dy: 30.0 * dy) 
       Bullet.physicsBody?.applyImpulse(vector) 


      } 
      spawnBullets() 
      Timer.scheduledTimer(timeInterval: 0.2, target: self, selector:#selector("spawnBullets"),userInfo: nil, repeats: true) 
     } 

' 然而,當我運行它,我得到的是選擇不引用任何錯誤。任何人都可以幫助我嗎? 謝謝

+0

目標/動作的選擇器必須在類的頂層,「let location = ...'這一行是瘋狂的。 – vadian

+0

是的。但是當我複製代碼時這只是一個錯誤 –

回答

0

您沒有添加您正在使用的swift版本。迅速3.x有一些小的變化。

在迅速3.X你不使用引號選擇以這種方式,所以你必須刪除引號&做這樣的事情:

selector:#selector(spawnBullets) 

這也給你某種類型的安全性時,改變你的代碼。所以,如果你做錯了某些事情,你會得到編譯時錯誤,而不是運行時錯誤。

我也會在你的情況做的是移動的功能spawnBullets touchBegan外面是這樣的:

func spawnBullets(_ location: CGPoint) { 
    ... 
} 

您還需要另一個單獨的FUNC處理定時器參數(更多信息在這裏:https://stackoverflow.com/a/41987413/404659 ):

func spawnBullets(sender: Timer) { 
    if let location = sender.userInfo as! CGPoint? { 
     spawnBullets(location) 
    } 
} 

你touchBegan然後將最終是這樣的:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    for touch in (touches) { 

     let location = touch.location(in: self) 
     spawnBullets(location) 
     Timer.scheduledTimer(
      timeInterval: 0.2, 
      target: self, 
      selector:#selector(spawnBullets(sender:)), 
      userInfo: location, 
      repeats: true 
     ) 

    } 
} 
相關問題