2015-08-22 97 views
-2

我有一个角色拍摄,我希望他只在用户触摸屏幕时拍摄,我不断收到此错误“'GameScene'没有名为'stimer'的成员 这里是代码如何停止NSTimer

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    /* Called when a touch begins */ 

    for touch: AnyObject in touches { 
     var stimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("spawnShot"), userInfo: nil, repeats: true) 
     let location = touch.locationInNode(self) 
     player.position.x = location.x 

    } 
} 
    override func touchesEnded(touches: Set<NSObject>, withEvent: UIEvent){ 
    for touch: AnyObject in touches{ 
     if self.stimer.valid{ 

      self.timer.invalidate() 
      self.timer = nil 
     } 

    } 
} 

回答

1

你的问题是,任何变量或常量的方法内声明的是仅在该方法可用。

我认为,这将解决这个问题,如果你宣布stimertouchesBeganvar stimer:NSTimer!,然后就传递你的观点,就像你在里做的那样。然后你可能不需要定时器名称前的self.

此外,它看起来像你正在失效一个不同的计时器比你检查的有效性?这可能是另一个问题,我不知道你是否故意这样做。

0

你应该在你GameScene init方法或以任何其他功能的初始启动计时器,这样的:

var gameLoop:NSTimer? 
var hitByEnemy:Bool = false 

// you need to implement this method otherwise Xcode will throw an error 
required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 

override init(size: CGSize) { 
    super.init(size: size) 
    self.gameLoop = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "gameLoopTimerTicked:", userInfo: nil, repeats: true) 
} 

,那么你需要创建在一定的时间间隔开始经过NSTimer将调用方法:

func gameLoopTimerTicked(timer:NSTimer){ 
    if self.hitByEnemy { 

     self.gameLoop?.invalidate() 
    } 
} 

在另一个函数中,你应该定义你的角色是否被敌人击中或任何其他应该停止你的计时器的事件。