Swift Ints和一些双打工作,但不是所有双打

时间:2016-02-28 02:11:52

标签: ios swift nstimer

我想要做的是提高方法spawnEnemy()被调用的速度,并且使用带星号的数字作为Ints可以很好地工作,但我觉得它过得太快所以我想到使用双打并使用小数点。但是,如果我进入从spawnRate中减去一定数量的十分之一 self.spawnRate=spawnRate - 1.0(我使用0以外的任何东西)spawnEnemy()只会在模拟器中调用一次,然后什么都不会发生。任何建议或意见都会很棒。谢谢!

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var scoreLabel: UILabel!

    var points: Int = 0

    var tickCount=0.0 //  **

    var spawnRate=15.0 // Spawn every 15 seconds to start with.....   **

    var spawnTimer:NSTimer!

    override func viewDidLoad() {

        super.viewDidLoad()

        self.tickCount=self.spawnRate

        self.spawnTimer=NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("tick"), userInfo: nil, repeats: true)

    }

    func tick() {
        if (--tickCount == 0) { // **
            self.spawnEnemy()
            self.spawnRate=spawnRate - 0.5 // Change this to determine how quickly the spawn rate increases.....    **
            self.tickCount=self.spawnRate
        }
    }
    func randomPoint() -> CGPoint {
        let randomPoint: CGPoint = CGPoint(x:CGFloat(arc4random()%320),y:CGFloat(568-arc4random()%390))
        return randomPoint
    }

    func randomColor() -> UIColor {
        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }

    func spawnEnemy() {
        let enemy: UIButton = UIButton(frame: CGRect(x: 160, y: 160, width: 100, height: 100))
        enemy.backgroundColor = randomColor()
        enemy.center = randomPoint()
        enemy.addTarget(self, action: Selector("buttonPushed:"), forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(enemy)
    }
    func buttonPushed(sender : UIButton) {
        if sender.frame.height < 50 || sender.frame.width < 50 {
            sender.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y, 50, 50)
            sender.backgroundColor = randomColor()
            sender.center = randomPoint()
            return
        }
        while sender.backgroundColor != UIColor.blackColor() {
            points = points + 1
            scoreLabel.textAlignment = .Center
            scoreLabel.text = "\(points)"
            scoreLabel.backgroundColor = UIColor.blackColor()
            sender.backgroundColor = UIColor.blackColor()
        }
    }
}

1 个答案:

答案 0 :(得分:4)

我认为您正在尝试使用相等运算符测试双精度。问题是总是有一点complexity in how doubles are stored,这使得用相等性比较它们非常困难。相反,你需要做这样的事情:

if (--tickCount <= 0) {

这样你就可以确定它会变为负数,否则它会越过0并继续倒计时。