Check if the player has hit a margin - swift

I'm making a little game using swift, a Snake Game. I've already tried to do this game using python and it worked! To run the game I used a while loop. In this way, I could always change the player position and check if he had hit the margins. Now I have to do this again, but I don't know how to tell to my program to check all the time if the snake has hit the margins or himself.
I should do something like that
if player.position.x <= 0 || player.position.x >= self.size.width || player.position.y <= 0 || player.position >= self.size.height{
death()
}
So, if the player position on x or y axis is major than the screen size or minor than 0, call the function "death()".
If I had to do this with python, I'd have just put all this code inside the "main while loop". But with swift there's not a big while I can use... any suggestions?

Use SpriteKit. You can select this when creating a new project, choose Game, and then select SpriteKit. It's Apple's framework to make games. It has what you will need, and is also faster - don't make games in UIKit.
Within SpriteKit, you have the update() method, as part of SKScene. Do NOT use a while loop. These are highly unreliable, and the speed of the snake will vary between devices.
Here is a small piece of code to help you get started on the SKScene:
import SpriteKit
class Scene: SKScene {
let timeDifference: TimeInterval = 0.5 // The snake will move 2 times per second (1 / timeDifference)
var lastTime: TimeInterval = 0
let snakeNode = SKSpriteNode(color: .green, size: CGSize(width: 20, height: 20))
override func update(_ currentTime: TimeInterval) {
if currentTime > lastTime + timeDifference {
lastTime = currentTime
// Move snake node (use an SKSpriteNode or SKShapeNode)
}
}
}
After doing all this, you can finally check if the snake is over some margins or whatever within this update() loop. Try to reduce the code within the update() loop as much as possible, as it gets run usually at 60 times per second.

If I understood you correctly: You are looking for a loop in Swift that does all the calculation and drawing for your game. Here you have some tutorials about loops in Swift. In fact there are while loops that you could use in order to answer your question. I hope I could help.

Related

Is there a way to add a fading trail or stroke to a moving SKSpriteNode?

Still new, but slowly building my first app/game, and am slowly getting there.
I'd like to be able to add a fading streak or trail as one of my SKSpriteNodes moves. Whether it is moving due to touchesMoved or being sent back to its original spot by code. I just want to add a nice visual effect.
The only thing I can think of is calculating the distance, breaking it down into x movements, then gradually move the Sprite a little, with some fade options, and then repeat in a loop till it gets back to home base, using a lot of nested SKActions and sequences.
I know that has to be wrong because it's just so ugly.
When I look at the Sprite Kit's Particle File, it has so few options. And I'm not really sure that's what I should be looking at. I have also looked at SKAction's options, and if there's an option there I'm missing it.
Surely in Swift's huge animation library there has to be something?
Let's create a basic sprite and an emitter, and make the emitter a child of the sprite so that it follows it:
let sprite = SKSpriteNode(color: .white, size: CGSize(width: 20, height: 10))
let emitter = SKEmitterNode() // better to use the visual designer in Xcode...
emitter.particleLifetime = 1.0
emitter.particleBirthRate = 50.0
emitter.particleSpeed = 100.0
emitter.emissionAngleRange = .pi / 5
emitter.particleTexture = SKTexture(imageNamed: "spark")
emitter.particleScale = 0.1
emitter.particleAlphaSpeed = -1.0
emitter.emissionAngle = -.pi
sprite.addChild(emitter) // attach it to the sprite
emitter.position.x = -15 // but not to the center
scene.addChild(sprite)
sprite.run(SKAction.group([ // let's run some actions to test it:
SKAction.sequence([
SKAction.move(to: CGPoint(x: 200, y: 200), duration: 5),
SKAction.move(to: CGPoint(x: 50, y: 50), duration: 5),
]),
SKAction.rotate(byAngle: .pi * 2.0, duration: 10)
]))
(Click to open animated GIF if it doesn't display correctly:)
To the casual observer, it looks fine… Except that, after some scrutiny, you'll realize what's off: the particles emitted live in the universe of the parent sprite, moving and rotating with it, even long after they were emitted! That's not right!
That's because the targetNode of the emitter is its parent, and it should be the scene!
So let's insert this line somewhere:
emitter.targetNode = scene // otherwise the particles would keep moving with the sprite
(Click to open animated GIF if it doesn't display correctly:)
Okay, this is a no-go: the particles now stay in the "universe" of the scene, but apparently their emission angle fails to follow that of the parent (which looks like a bug to me).
Luckily, we can attach a custom action to the emitter which keeps aligning this angle to the parent sprite:
emitter.run(SKAction.repeatForever(
SKAction.customAction(withDuration: 1) {
($0 as! SKEmitterNode).emissionAngle = sprite.zRotation + .pi
_ = $1
}))
(Click to open animated GIF if it doesn't display correctly:)
Okay, now new particles are launched in the correct direction, and keep moving that way even if the sprite moves or rotates in the meantime. This seems to be the most realistic simulation so far, though there may still be ways to improve it by modifying the behavior of the emitter on the fly.
Sorry for the jaggy GIFs, apparently my Mac is too slow to render and capture at the same time. The animations themselves run just fine.

How to make a delay in a loop in SpriteKit?

I have made some search here and there but I didn't find (or understand) how to make a delay in a loop in SpriteKit.
This is the idea : I have some SKSpriteNodes sorted in an array and I want to display them on the screen, one every second. The problem is... I simply don't manage to do it (sorry, I'm quite new to this).
let sprite1 = SKSpriteNode(color: .red, size: CGSize(width: 20, height: 20))
sprite1.position = CGPoint(x: 100, y: 100)
let sprite2 = SKSpriteNode(color: .red, size: CGSize(width: 20, height: 20))
sprite2.position = CGPoint(x: 100, y: 300)
let sprite3 = SKSpriteNode(color: .red, size: CGSize(width: 20, height: 20))
sprite3.position = CGPoint(x: 300, y: 100)
let sprite4 = SKSpriteNode(color: .red, size: CGSize(width: 20, height: 20))
sprite4.position = CGPoint(x: 300, y: 300)
let allSprites : [SKSpriteNode] = [sprite1, sprite2, sprite3, sprite4]
let delay = 1.0
var i = 0
while i <= 3
{
let oneSprite = allSprites[i]
self.addChild(oneSprite)
DispatchQueue.main.asyncAfter(deadline : .now() + delay) {
i = i + 1
}
}
If you're asking : this doesn't work at all. It seems that what is inside the DispatchQueue.main.asyncAfter isn't read.
So, if you can help me to understand why, that would be great. I'm not picky, I can't take the answer with a "for" loop.
Regards,
This is a common beginner misunderstanding of event-driven / run-loop-based / GUI programming systems. Some key points to help get on the right track:
SpriteKit is trying to render the scene 60 (or so) times per second.
That means SpriteKit internally has a loop where, once per frame, it calls your code asking what's new (update), then runs its own code to draw the changes (render).
Setup code, or things that happen in response to events (clicks/taps/buttons) are external to this loop, but feed into it: events change state, which the render loop reacts to.
So, if you have a loop in an update method, an event handler, or initial setup code, everything that happens in that loop will happen before SpriteKit gets a chance to draw any of it. That is, if we ignore for a moment the "delay" part of your question, a loop like this...
var i = 0
while i <= 3 {
let oneSprite = allSprites[i]
self.addChild(oneSprite)
}
... will result in none of the sprites being visible right before the loop starts, and all of the sprites being visible after it completes. No amount of introducing delays within the loop will change that, because SpriteKit doesn't get its first chance to draw until after your loop is finished.
Fixing the problem
The best way to do animations and delays in a system like SpriteKit is to make use of the tools it gives you for treating animation declaratively. That is, you tell SpriteKit what you want to have happen over the next several (hundred) frames, and SpriteKit makes that happen — each time it goes through that update/render loop, SpriteKit determines what changes need to be made in the scene to accomplish your animation. For example, if you're running at 60 fps, and you ask for a fade-out animation on some sprite lasting one second, then each frame it'll reduce that sprite's opacity by 1/60.
SpriteKit's tool for declarative animations is SKAction. There are actions for most of the things you'd want to animate, and actions for composing other actions into groups and sequences. In your case, you probably want some combination of the wait and unhide and run(_:onChildWithName) actions:
Give each of your sprites a unique name:
let sprite1 = // ...
sprite1.name = "sprite1"
// etc
Add all the nodes to your scene, but keep the ones you don't want visible yet hidden:
let allSprites : [SKSpriteNode] = [sprite1, sprite2, sprite3, sprite4]
for sprite in allSprites {
sprite.isHidden = true
self.addChild(sprite)
}
Create a sequence action that alternates delays with telling each node to unhide, and run that action on your scene:
let action = SKAction.sequence([
run(.unhide(), onChildNodeWithName: "sprite1"),
wait(forDuration: 1.0),
run(.unhide(), onChildNodeWithName: "sprite2"),
wait(forDuration: 1.0),
// etc
])
self.run(action)
That should accomplish what you're looking for. (Disclaimer: code written in web browser, may require tweaking.) Read on if you want to better understand the situation...
Other alternatives
If you really want to get your head around how the update/render loop works, you could participate directly in that loop. I wouldn't recommend it in general, because it's a lot more code and bookkeeping, but it's useful to know.
Keep a queue (array) of nodes that you want to add or unhide.
In you scene's update method, keep track of how much time has passed.
If it's been at least 1.0 second (or whatever delay you're after) since you last showed a node, add the first one in the array, and remove it from the array.
When the array is empty, you're done.
About DispatchQueue.asyncAfter...
This isn't essential to completing your task, but helpful to understand so you don't get into similar problem later: the word "async" in the call you were using to try delaying things is short for "asynchronous". Asynchronous means that the code you're writing doesn't execute in the order you write it in.
A simplified explanation: Remember that modern CPUs have multiple cores? When CPU 0 is executing your while loop, it gets to the asyncAfter call and passes a note to CPU 1 saying to wait one second and then execute the closure body attached to that asyncAfter call. As soon as it passes that note, CPU 0 continues merrily on its way — it doesn't wait for CPU 1 to receive the node and complete the work that note specifies.
Just from reading the code, I'm not 100% clear on how this approach fails, but fail it certainly does. Either you have an infinite loop, because the while condition never changes, because the work to update i is happening elsewhere and not propagating back to local scope. Or the the changes to i do propagate back, but only after the loop spins an indeterminate number of times waiting for the four asyncAfter calls to finish waiting and execute.

SKEmitterNode: altering birth rate on update not adding more particles

I have an SKEmitterNode on my scene, when I increase the particles on update, the amount of particles being shown are not increasing. I am not sure what step I am missing.
The code is really simple:
Create any kind of default particle from Xcode.
Set birthrate to 1, max to 0
Everything else doesn't really matter.
On GameScene update:
func update(currentTime: NSTimeInterval) {
//whatever it takes to get the particle from the scene
let particles = childNodeWithName("particles") as? SKEmitter
particles!.particleBirthRate = particles!.particleBirthRate + 1;
}
Note: When doing a print, the birth rate does increase, so I know it is not using a copy

Spawn nodes at random times combing waitForDuration:withRange and runBlock: in an SKAction sequence

I am making a game with SpriteKit where I have nodes spawning at the top of the screen and falling. However, I want these nodes to spawn at a random time interval between 0.1 and 3 seconds. For example, the first node spawns in 1.3 seconds, the next in 1.8, then 2.5, then 0.8, and so forth forever. I'm not sure how to utilize the waitForDuration function to do this. The code that I currently have is:
let wait = SKAction.waitForDuration(3, withRange: 2)
let spawn = SKAction.runBlock { addTears()
}
let sequence = SKAction.sequence([wait, spawn])
self.runAction(SKAction.repeatActionForever(spawn))
This code freezes my game when I try to run it. I removed the addTears() and put a log, and there was an infinite loop on the log. I need to know how to get rid of this.
The code for my addTears() func is:
func addTears() {
let Tears = SKSpriteNode (imageNamed: "Tear")
Tears.position = CGPointMake(Drake1.position.x, Drake1.position.y - 2)
Tears.zPosition = 3
addChild(Tears)
//gravity
Tears.physicsBody = SKPhysicsBody (circleOfRadius: 150)
Tears.physicsBody?.affectedByGravity = true
//contact
Tears.physicsBody = SKPhysicsBody (circleOfRadius: Tears.size.width/150)
Tears.physicsBody!.categoryBitMask = contactType.Tear.rawValue
Tears.physicsBody!.contactTestBitMask = contactType.Bucket.rawValue
}
If I remember well, the waitForDuration:withRange: method works like so :
if you put a duration of 3 (seconds) and a range of 1 seconds the random value that you get will be between 2 and 4 seconds. That said, you should use those value for what you described : let wait = SKAction.waitForDuration(1.55, withRange: 1.45)
For the freeze problem, if you pasted your code correctly here the problem come with this line self.runAction(SKAction.repeatActionForever(spawn)) where you should instead be calling your sequence like this : self.runAction(SKAction.repeatActionForever(sequence)).
PS : At a certain point you still might want to control the amount of tears on screen at the same time.
Let me know if it helped.

Flipping a child sprite's xscale in Spritekit using Swift

Alright I'm offically stumped. I've been able to figure out my problems myself in the past but I'm lost on this one.
I'm trying to flip a child sprite's xscale. I want the flip to occur when the child's x position is negative. With the code below, the sprite does flip, every time the sprite reaches negative position, it loops back and forth flipping until reaching positive again.
I've tried numerous variations, but this is the code in it's simplest form. Any help or alternatives would be appreciative.
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
let pin = childNodeWithName(Pin1) as SKSpriteNode!
let guyPoint = guy.convertPoint(guy.position, fromNode: pin)
if guyPoint.x <= 0 {
guy.xScale = -1
}
else {
guy.xScale = 1
}
}
So if it is constantly flipping it's probably an issue of coordinate space. So check to make sure your convertPoint method is accurately returning the point you want. I would use println() to see what's going on there.
Probably what's happening is you want to flip the xScale when the child node is negative in the scene space or something (i.e. when the child is off the screen) but instead guyPoint might be the position of the child in its parent's coordinate space (so relative to the parent).
Also try with and without the else{} part to see if that changes anything.