scheduleTimerWithTimeInterval

scheduleTimerWithTimeInterval

我正在尝试制作带有弹跳球的游戏,我想每8秒生成一个球。目前,它在生成后不会移动。我的问题是,在第一个球生成后,应用程序在接下来的5秒钟内崩溃。我不确定为什么会这样。我将scheduleTimerWithTimeInterval()放在touchesBegan函数中。

func scheduledTimerWithTimeInterval(){
    Enemytimer = Timer.scheduledTimer(timeInterval: 8, target:self, selector:#selector(GameScene.spawnEnemies), userInfo:nil, repeats:true)
}
func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{
    return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
}

func spawnEnemies(){
    let xPos = randomBetweenNumbers(firstNum: 0, secondNum:frame.width)
    let yPos = randomBetweenNumbers(firstNum: 0, secondNum: frame.height)
    enemies.size = CGSize(width: 20, height:20)
    enemies.color = UIColor(red:255.0,green:0.0,blue:0.0,alpha:1.0)
    enemies.colorBlendFactor = 1.0
    enemies.position = CGPoint(x: xPos, y:yPos)
    enemies.physicsBody?.affectedByGravity = false
    self.addChild(enemies)

最佳答案

您最有可能遇到内存问题。我将把scheduleTimerWithTimeInterval方法移出touchesBegan。现在,每次用户触摸屏幕时,游戏都会启动一个新的计时器(无需启动其他计时器)。将scheduleTimerWithTimeInterval移动到viewDidLoad或类似startGame的内容,以确保仅被调用一次。

关于swift - 应用运行后崩溃?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44009429/

10-11 05:41