Timer


import UIKit
import SpriteKit


class GameScene: SKScene, SKPhysicsContactDelegate {
 var toggle:Bool = true
  var lastUpdateTime : TimeInterval = 0
  var label: SKLabelNode!
  var myTimer = Timer()
  let timeLabel  = SKLabelNode(fontNamed: "Verdana-bold")
  var timeCount = 10

  override func didMove(to view: SKView) {
  backgroundColor = .yellow
  self.physicsWorld.contactDelegate = self
  self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
  physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)
  let ball = SKShapeNode(circleOfRadius: 40) //circleOfRadiusで円の半径
  ball.position = CGPoint(x:self.frame.midX, y:self.frame.midY+100)
  ball.fillColor = UIColor.white
  ball.lineWidth = 0.0
  ball.strokeColor = UIColor.red
  ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width/2)
  self.addChild(ball)
  //ボールの飛んでいく方向
  ball.physicsBody?.applyImpulse(CGVector(dx: 40, dy: 40))
  ball.physicsBody?.affectedByGravity = false
  ball.physicsBody?.isDynamic = true
  ball.physicsBody?.friction = 0
  ball.physicsBody?.restitution = 1

timeLabel.text = "Count:\(timeCount)"
    //timeLabelが動かないようにleft固定
    //  timeLabel.horizontalAlignmentMode = .left
    timeLabel.fontSize = 50
    timeLabel.fontColor = SKColor.black
  timeLabel.position = CGPoint(x: self.frame.midX, y: self.frame.midY )
    self.addChild(timeLabel)
    // タイマーをスタートする(1.0秒ごとにtimerUpdateを繰り返し実行)
  myTimer = Timer.scheduledTimer(
     timeInterval: 1.0,
     target: self,
     selector: #selector(timerUpdate),
     userInfo: nil,
     repeats: true)
}

@objc func timerUpdate() {
   timeCount -= 1
   timeLabel.text = "Count:\(timeCount)"
if timeCount < 0 {
 myTimer.invalidate()
 self.timeLabel.isHidden = true
  // let scene = GameScene2(size: self.frame.size)
 //  let transition = SKTransition.moveIn(with: SKTransitionDirection.right, duration: 1.5)
 //  self.view?.presentScene(scene, transition: transition)
    let scene = GameScene2(size: self.frame.size)
    scene.scaleMode = scaleMode
    self.view!.presentScene(scene, transition: .doorsCloseVertical(withDuration: 0.8))    
   }
}
    
func fireTimer() {
    let date:Date = Date()
    let format = DateFormatter()
   format.dateFormat = "yyyy/MM/dd HH:mm:ss"
   let sDate = format.string(from: date)
    label = SKLabelNode(fontNamed: "Avenir-Black")
    label.text = sDate
    label.position = CGPoint(x: self.frame.midX, y: self.frame.midY + 50)
    label.fontSize = 20
    label.fontColor = SKColor.blue
    self.addChild(label)
 }
func toggleTest() {
   if(toggle){
 fireTimer()
   toggle = false;
 }else{
   label.removeFromParent()
   toggle = true;
 }
}
    
override func update(_ currentTime: TimeInterval) {
  if (lastUpdateTime == 0) {
  self.lastUpdateTime = currentTime - 0.5
   }
  if (currentTime - lastUpdateTime > 1) {
    toggleTest()
    lastUpdateTime = currentTime - 0.5
  }
}
}