I'm trying to create Ninjump like game using Swift UIKit. everything was working fine until i added scores label. This is actually weird and I can't figure out why its happeing.
So I have a enemy which movies 15px down when timer updates. and One ninja, which moves from left to right when touched on screen. And Score updates when enemy moves out of screen. Whats happening is, score is updating to 1...2..3 when enemies go out of screen. But whenever the score is updating, Ninja moves to left automatically if at right. I don't know why its happening. Its happening everytime when one enemy goes out of the screen. Here's my code
import UIKit
class GameViewController: UIViewController {
@IBOutlet weak var Ninja: UIImageView!
var score = 0
@IBOutlet weak var scoreLabel: UILabel!
var startGame = NSTimer()
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.updateNinja()
}
var enemyImage = UIImageView(frame: CGRectMake(32, -300, 100, 100))
override func viewDidLoad() {
super.viewDidLoad()
self.scoreLabel.text = "0"
enemyImage.image = UIImage(named: "enemy")
self.view.addSubview(self.enemyImage)
}
override func viewDidAppear(animated: Bool) {
startGame = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func update() {
if CGRectIntersectsRect(self.Ninja.frame, self.enemyImage.frame) {
println("Game Over")
}
// show the enemy again and again
if self.enemyImage.frame.origin.y > self.view.frame.height {
self.enemyImage.frame.origin.y = -100
score++ // THIS IS THE PROBLEM
self.scoreLabel.text = "\(score)"
}
// move the enemy image downwards
enemyImage.frame.origin.y += 15
}
var isLeft:Bool = false // check where is the ninja left/right
func updateNinja() {
if isLeft {
isLeft = false
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.Ninja.frame.origin.x = 32
})
} else {
isLeft = true
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.Ninja.frame.origin.x = self.rightBar.frame.origin.x - 50
})
}
}
}
and whats more weird is when I remove score++ its working fine.
Update: Its happeing when I'm trying to update the scoreLabel's text. any solution?
hide that label and try creating a new label programatically, update the new label for scores. Let me know if it works for you, It happened to me once as well.