Spawn Overlap within Swift - swift

I am making a game using SpriteKit, and I have two SKSpriteNodes that are being spawned in using a gameTimer for each SKSpriteNode.
Is there a way to prevent the nodes from spawning on top of each other when using timers in order to spawn them onto the screen? Here's my code if needed. addObstacle and updateTimer are the functions that actually spawn the nodes.
//adds new obstacles every obstacleInterval seconds
gameTimer = Timer.scheduledTimer(timeInterval: TimeInterval(obstacleInterval), target: self, selector: #selector(addObstacle), userInfo: nil, repeats: true)
//adds new enemies every enemyInterval seconds
gameTimer = Timer.scheduledTimer(timeInterval: TimeInterval(enemyInterval), target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)

Related

Create a timer that pauses the code's flow Swift

Does a timer like let timer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: false) actually stops the code for 10 seconds? Or will the code behind keeps running? I need a timer that could pause the code's flow for 10 seconds, and I don't want to use sleep or a closure! How can I implement this? Thanks.
You can probably use a Bool and the Timer in combination.
Take 2 Timers.
Timer1 - would at equal intervals call a method which internally checks the flag and would perform / not perform the action.
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
func fireTimer() {
if self.blockCode { return }
// your code here
}
Timer2 - would toggle the flag after a given set time, lets say 10 seconds.
self.blockCode = true
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
self?.blockCode = false
}
This would make you stop a code from execution for a fixed set of time without actually freezing the app like sleep would do.
Hope this helps.

How do i make the label change text on its own and delay too - swift?

I need the label to change every 5 seconds on its own like a slideshow I am working with swift 3
.
Create a Timer and make the changes you need inside the function that is called by the timer.
var timer:Timer!
timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.countDown), userInfo: nil, repeats: true);
var getLocationtimer:Timer = Timer()
self.getLocationtimer = Timer.scheduledTimer(timeInterval: 5, target:self, selector:#selector(YOUR_VIEW_CONTROLLER.updateLevel), userInfo:nil, repeats:true)
func updateLevel(){
//Update label your here
}
This timer can help you achieve what you are trying to.

Trying to get NSTimers to synchronise when they are fired swift

I am trying to create a game where the user has to navigate a ball through gaps in platforms (known as fall down). When the score reaches a certain point, the moving platforms are created at a faster rate. To achieve this I wrote the code below:
switch String(level) {
case "1" :
beginLevel.invalidate()
level1 = NSTimer.scheduledTimerWithTimeInterval( 0.9 , target: self, selector: Selector("platformCreation"), userInfo: nil , repeats: true)
case "2" :
level1.invalidate()
level2 = NSTimer.scheduledTimerWithTimeInterval( 0.8 , target: self, selector: Selector("platformCreation"), userInfo: nil , repeats: true)
case "3" :
level2.invalidate()
level3 = NSTimer.scheduledTimerWithTimeInterval( 0.7 , target: self, selector: Selector("platformCreation"), userInfo: nil , repeats: true)
case "4" :
level3.invalidate()
level4 = NSTimer.scheduledTimerWithTimeInterval( 0.6 , target: self, selector: Selector("platformCreation"), userInfo: nil , repeats: true)
default :
print("invalid level")
}
beginLevel is ran whenever the game restarts, and level can only be 1- 4.
The issue I am having with this is that once the previous NSTimer is invalided, there is a delay where no platforms are created, before the new one is fired. These delays make the game too easy and in all honestly it looks ugly too! Which I'm trying to achieve is a constant flow of platforms with no huge gaps between platforms. Anything you can offer to this issue is hugely appreciated.
One possible solution is to invalidate the old timer after an appropriate delay.
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.level1.invalidate()
}
One solution is to use call fire() method immediately after initializing of timer as give below
level3 = NSTimer.scheduledTimerWithTimeInterval( 0.7 , target: self, selector: Selector("platformCreation"), userInfo: nil , repeats: true);
level.fire()

NSTimer time interval not firing correctly

I have an NSTimer that calls a function. The function flashes a different button each time it is called. i have the time interval set to one second and repeats is true, it stops repeating when the variable pcChoice == 10, but for some reason when i run the program it is delaying for a second and then calling the function a number of times right after each other. To the user, it looks like one second passes, then a number of buttons are flashed at once. What I need instead is for each button to flash one after another, with one second in between each flash.
override func viewDidLoad() {
var lit = [b0o,b1o,b2o,b3o,b4o,b5o,b6o,b7o,b8o]
var litIndex = 0
super.viewDidLoad()
for i in 1...10{
print(randomIndex)
print(computerChoices)
var buttonChoice = lit[randomIndex]
randomIndex = Int(arc4random_uniform(UInt32(lit.count)))
computerChoices[i] = randomIndex
print("yoyoyo")
self.view.setNeedsDisplay()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("flashingButtons"), userInfo: nil, repeats: true)
}
}
func flashingButtons(){
var lit = [b0o,b1o,b2o,b3o,b4o,b5o,b6o,b7o,b8o]
one = computerChoices[pcChoice]
lit[one].setImage(UIImage(named: "redb.png"), forState: UIControlState.Normal)
pcChoice += 1
if pcChoice == 10{
timer.invalidate()
}
}
This line
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("flashingButtons"), userInfo: nil, repeats: true)
is executed 10 times because of your for loop. That gives you 10 different timers, each of which will invoke flashingButtons in about 1 second from now. Move that call out of the loop. You also don't need 10 calls to setNeedsDisplay in viewDidLoad.
Since you don't modify lit, make it a let instead of a var. I notice also that you have 9 elements in lit but you're looping through 10 times. The lit array in viewDidLoad is never used, and is different from the one in flashingButtons.
You could invoke arc4random_uniform inside flashingButtons each time the time fires. Or if you want the lights truly shuffled, each one being hit once, try something like this using GameplayKit:
let lit = [b0o,b1o,b2o,b3o,b4o,b5o,b6o,b7o,b8o]
let shuffledLit : [<lightobjects>] // whatever type of b0o, etc is
override func viewDidLoad() {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("flashingButtons"), userInfo: nil, repeats: true)
shuffledLit = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(lit)
super.viewDidLoad()
self.view.setNeedsDisplay()
}

SpriteKit - NSTimer showing error

I'm building a simple game and I want a "Square" to shoot from the left and side to the middle of the screen, where my "MainSquare" is. I'm using an NSTimer and making this square shoot from the left to the center every second. Even though this NSTimer has a purpose, running my "LeftShot" function, it's still coming up with the famous and annoying
"initialisation of variable 'timer' was never used".
Help? :(
in my did move to view:
var Timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("LeftShot"), userInfo: nil, repeats: true)
the function the timer runs every second:
func LeftShot(){
let EnemySquareLeft = SKSpriteNode(imageNamed: "Square2")
EnemySquareLeft.size = CGSize(width: 30, height: 30)
EnemySquareLeft.position = CGPoint(x: frame.width / 2 - 231, y: frame.height / 2)
let action = SKAction.moveTo(MainSquare.position, duration: 1)
EnemySquareLeft.runAction(SKAction.repeatActionForever(action))
self.addChild(EnemySquareLeft)
}
I think this error is just a yellow coloured error? If so, you can ignore it, or in the didMoveToView just change the declaration of timer to
_ = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("LeftShot"), userInfo: nil, repeats: true)
Xcode encourages you to do this when you are not using the name of the variable (or constant) anywhere else.
However, if you will use some property of your timer within the didMoveToView, change the declaration to
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("LeftShot"), userInfo: nil, repeats: true)