2017-01-26 6 views
2

Извините быть неуклюжим, но, пожалуйста, я могу иметь полный код о том, как это сделать:Swift Таймер Проверить TouchesEnded

Я хотел бы задержку в 1 секунду после того, как каждая пуля снимается в моей игре, чтобы предотвратить пули спама. Если возможно, не создавая отдельную функцию для нереста пули, как я сделал это в touchEnded. Так коснитесь, стреляйте, ждите. коснитесь, стреляйте, ждите. И в ожидании, если экран прослушивается, ничего не происходит. Спасибо и жаль, что я новичок

guard let touch = touches.first else { 
     return 
    } 
    let touchLocation = touch.location(in: self) 

    //Set up initial location of bullet and properties 
    let bullet = SKSpriteNode(imageNamed: "bullet") 
    bullet.name = "Bullet" 
    bullet.position = player.position 
    bullet.setScale(0.75) 
    bullet.zPosition = 1 
    bullet.physicsBody = SKPhysicsBody(circleOfRadius: bullet.size.width/2) 
    bullet.physicsBody?.isDynamic = true 
    bullet.physicsBody?.categoryBitMask = PhysicsCategory.Projectile 
    bullet.physicsBody?.contactTestBitMask = PhysicsCategory.Monster 
    bullet.physicsBody?.collisionBitMask = PhysicsCategory.None 
    bullet.physicsBody?.usesPreciseCollisionDetection = true 



    //Determine offset of location to bullet 
    let offset = touchLocation - bullet.position 

    //Stops Bullet from shooting backwards 
    if (offset.y < 0) { return } 

    addChild(bullet) 

    //Get the direction of where to shoot 
    let direction = offset.normalized() 

    //Make it shoot far enough to be guaranteed off screen 
    let shootAmount = direction * 1000 

    //Add the shoot amount to the current position 
    let realDest = shootAmount + bullet.position 

    //Create the actions 

    if currentGameState == gameState.inGame { 
    let actionMove = SKAction.move(to: realDest, duration: 1.2) 
    let actionMoveDone = SKAction.removeFromParent() 
    bullet.run(SKAction.sequence([actionMove, actionMoveDone])) 
    } 

} 

ответ

2

Попробуйте это:

var fired = false 

// Other code... 

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    guard let touch = touches.first else { 
     return 
    } 
    let touchLocation = touch.location(in: self) 

    if fired == false { 

     fired = true 

     //Set up initial location of bullet and properties 
     let bullet = SKSpriteNode(imageNamed: "bullet") 
     bullet.name = "Bullet" 
     bullet.position = player.position 
     bullet.setScale(0.75) 
     bullet.zPosition = 1 
     bullet.physicsBody = SKPhysicsBody(circleOfRadius: bullet.size.width/2) 
     bullet.physicsBody?.isDynamic = true 
     bullet.physicsBody?.categoryBitMask = PhysicsCategory.Projectile 
     bullet.physicsBody?.contactTestBitMask = PhysicsCategory.Monster 
     bullet.physicsBody?.collisionBitMask = PhysicsCategory.None 
     bullet.physicsBody?.usesPreciseCollisionDetection = true 



     //Determine offset of location to bullet 
     let offset = touchLocation - bullet.position 

     //Stops Bullet from shooting backwards 
     if (offset.y < 0) { return } 

     addChild(bullet) 

     //Get the direction of where to shoot 
     let direction = offset.normalized() 

     //Make it shoot far enough to be guaranteed off screen 
     let shootAmount = direction * 1000 

     //Add the shoot amount to the current position 
     let realDest = shootAmount + bullet.position 

     //Create the actions 

     if currentGameState == gameState.inGame { 
      let actionMove = SKAction.move(to: realDest, duration: 1.2) 
      let actionMoveDone = SKAction.removeFromParent() 
      bullet.run(SKAction.sequence([actionMove, actionMoveDone])) 

     } 

     run(SKAction.wait(forDuration: 1), completion: { fired = false }) 

    } 
} 

Это означает, что каждый раз, когда пуля срабатывает, таймер на 1 секунду происходит что предотвращает код пули от бежится до Время вышло. В этот момент логическое значение Boolean переключается на значение false, позволяя повторить запуск кода.