SpriteKit. A change from optional to force unwrap crashes the app - sprite-kit

I’m following a tutorial for SpriteKit that has a problem with an IF statement. The logic of the line is as follows: If the bullet and the asteroid collide then remove them.
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid {
// remove bullet and asteroid
}
The problem arises when trying to make sure that the asteroid (body2.node) is inside the playable area before it can get shut down. For that, the author adds the following:
body2.node?.position.y < self.size.height
Making the complete IF statement as follows:
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid && body2.node?.position.y < self.size.height {
// remove bullet and asteroid
}
Apparently that line works with Swift 2 however Swift 3 makes a correction changing the position from an optional and force unwraps the position.
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid && body2.node!.position.y < self.size.height {
// remove bullet and asteroid
}
By force unwrapping the position, the app crashes “I THINK” when the three bodies collide. It is really difficult to tell when looking at the screen.
I’m testing the code below and I have not encounter any problems as of yet. Do you guys think that the fix below will work? What I'm thinking is, if I make sure the body2.node is not nil, then there is no reason why the app should crash since is not going to encounter a nil upon trying to force unwrap it.
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid {
// If the bullet has hit the asteroid
if body2.node != nil {
if ( body2.node!.position.y < self.size.height ) {
// remove bullet and asteroid
}
}
}
Or else, if there another way you guys can suggest a different way to write the original IF Statement?
Thanks

Yes, the if != nil statement (as it is currently written) will protect against force-unwrap-induced crashes.
An alternative is to use the if let syntax in Swift:
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid {
// If the bullet has hit the asteroid
if let body2Node = body2.node {
if body2Node.position.y < self.size.height {
// remove bullet and asteroid
}
}
}
The benefit is that it removes the ! from your code, and more clearly connects the nil check with the variable you are using later.

nathan has the right answer, but a better alternative would be to use a guard instead to protect your function:
...
guard let body1Node = body1.node, let body2Node = body2.node else {return}
//Beyond this point we need to guarentee both nodes exist
if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid {
// If the bullet has hit the asteroid
if body2Node.position.y < self.size.height {
// remove bullet and asteroid
}
}
By using a guard, we reduce nesting, and we know that beyond this point, the physics body must contain a node, unless we remove it before the function ends, which will eliminate any further need to check if the node exists.
As a side note, I always recommend to remove nodes at the end of your update phase to avoid issues like this, and instead just mark the node somehow that you will no longer be using it.

Related

How to refer to multiple SKNodes at once in SpriteKit?

In order to prevent a lot of the same code, I want to refer to every single node(all children of the same parent) on the scene with one call. I have a gate at the bottom of the scene and I want to detect if any node(many different nodes getting added to the scene) passes the y position of this gate.
This is how my update function looks now:
override func update(_ currentTime: TimeInterval) {
// code I want to simplify
if Cap.position.y < illustration2.position.y
|| Cap2.position.y < illustration2.position.y
|| Cap3.position.y < illustration2.position.y
|| Cap4.position.y < illustration2.position.y
|| Cap5.position.y < illustration2.position.y
|| Cap6.position.y < illustration2.position.y
|| Cap7.position.y < illustration2.position.y
|| Cap8.position.y < illustration2.position.y
|| Cap9.position.y < illustration2.position.y
|| Cap10.position.y < illustration2.position.y {
// Transitioning to game over
let transition = SKTransition.crossFade(withDuration: 0)
let gameScene = GameOver(size: self.size)
self.view?.presentScene(gameScene, transition: transition)
}
}
All Caps are children of illustration2, so I was thinking about something like:
//if the y position of any child is below the illustration2 y position the game over scene starts
if dontaiIllustration2.children.position.y < dontaiIllustration2.position.y {
}
Or another approach could be to check that the illustration2 node has the lowest y position from all nodes at the scene.
You can’t. You need to place them into a collection (array, dictionary, set, etc) and then find a way to traverse through them with something like foreach, map, compactMap (formally flatMap), reduced, etc. in your case, I would use reduce.
let caps = [Cap1,Cap2,Cap3,Cap4,Cap5,Cap6,Cap7,Cap8,Cap9,Cap10]
let result = caps.reduce(false,{value,cap in return value || cap.position.y < illustration2.position.y})
if result {
// Transitioning to game over
let transition = SKTransition.crossFade(withDuration: 0)
let gameScene = GameOver(size: self.size)
self.view?.presentScene(gameScene, transition: transition)
}
What this is doing, is going through each of your nodes, and evaluating the current equation with the previous result.
So we start at a false, then it will check if cap y > illustration y. If true, then our value becomes true, and this value carries over to the next cap. It repeats this until you run out of caps, and then returns the final value, which will be a false or a true.
Not really proud of this but you can do a forEach on the children of a parent node.
let node = SKNode()
var checker = false
node.children.forEach { (node) in
if node.position.y < illustration2.position.y {
checker = true
}
}
if checker {
// Game over
}
or you can enumerate them if you only want targets with specific names:
node.enumerateChildNodes(withName: "all can have same name") { (node, stop) in
if node.position.y < illustration2.position.y {
checker = true
}
}
You could also one-line it by using filter:
node.children.filter({$0.position.y < illustration2.position.y}).count > 0
Either way, i would put this in an extension of SKNode.

Swift: If SKNode color matches background color

I'm currently learning swift and i'm having some difficulty.
In my game a random background color changes every time to a random color between Red Green and Blue.
let colorgen = arc4random_uniform(3)+1
if colorgen == 1{
Col = UIColor.redColor()
}
else if colorgen == 2{
Col = UIColor.greenColor()
}
else if colorgen == 3{
Col = UIColor.blueColor()
}
It works pretty well but I know its not the best way to do things.
The game is pretty straight forward, a object can pass through either 3 walls. One green, one red, one blue. However the object can only pass through one wall at a time and that walls color MUST match the background color.
Here is what I tried to do:
override func update(currentTime: CFTimeInterval) {
if segment.color == self.backgroundColor{
segment.physicsBody?.collisionBitMask = 0
}
}
The code above is in the gamescene swift class
The effect is supposed to knock the walls out of place (only when the object hits the wrong color wall, making it fly away with its enabled collision bit mask) indicating a game over.
I only want the walls to have the ability to be knocked out physically when hit if the background color and wall being hit does NOT match (Basically wrong wall getting hit/touched by object). Thus that is why im using collision bit mask so that the current matching correct wall can still register the contact but the object goes right through it (setting it to 0). Exactly how I want it to be.
However collisionBitMask = 0 seems to have no effect on ALL the walls at all times.
My segment code is in another class called MovingGround and was made like this:
for i in 0 ..< NumberSeg {
//NumberSeg = 3 So that means 3 walls on screen
if i == 1{
segmentColor = colorone
//ColorX is just UIColors of Red Green and Blue
}
else if i == 2{
segmentColor = colortwo
}
else{
segmentColor = colorthree
}
segment = SKSpriteNode(color: segmentColor, size: CGSizeMake(self.size.width / CGFloat(NumberSeg), self.size.height))
segment.anchorPoint = CGPointMake(0.5, 0.5)
segment.position = CGPointMake(CGFloat(i)*segment.size.width+50, 0.5)
addChild(segment)
segment.physicsBody = SKPhysicsBody(rectangleOfSize:CGSizeMake(self.size.width/3,
15))
segment.physicsBody?.categoryBitMask = heroCategory
segment.physicsBody?.contactTestBitMask = wallCategory
segment.physicsBody?.affectedByGravity = false
segment.physicsBody?.velocity = CGVectorMake(0, 0)
segment.physicsBody?.usesPreciseCollisionDetection = true
It's weird, when I try:
if segment.color == UIColor.blueColor(){
segment.physicsBody?.collisionBitMask = 0
}
or
if self.backgroundColor == UIColor.blueColor(){
segment.physicsBody?.collisionBitMask = 0
}
To test if they work individually, they do!
I just don't understand why if I try to put them together with either a nested if statement or a single if with the && operator it won't work!
I should also mention I made the segment variable global (At least I think that's what its supposed to do) by putting it outside of Constants (Which is another separate file) swift class by:
var segment: SKSpriteNode!
I'm 14 & pretty new to Swift with not much programming knowledge except for a little bit of Python. So if anyone could help me figure this out that would be great!

Using && In an If Statement Swift 2.0

I am trying to make a very basic console game of rock paper scissors. I'm not sure how to go about using && in Swift 2.0. I want to basically say:
if (computerChoice == rock && userChoice == paper) {
print("User wins")
}
Well you appear to have it setup correctly. You could set this up using an enumeration variable.
enum RPSOption {
case Rock, Paper, Scissors
}
Then you just use it like so:
let computerChoice: RPSOption = RPSOption.Rock // or something else
let userChoice: RPSOption = RPSOption.Paper // or something else
if( computerChoice == .Rock && userChoice == .Paper ){
// do something
}
// do similar if statements for other conditions

Unexpected nil found when wrapping an optional variable

I keep getting this error and ive set conditions so that the bodyB is not nil when it is to be removed from its parent. However I still get this on going problem whilst running the app. I can wrap it using "?" instead but it duplicated the bodyB node (I recreate it after destroying it using the func createNewDart) Any ideas as why this is occuring
if contact.bodyA.categoryBitMask == BoardCategory && contact.bodyB.categoryBitMask == DartCategory {
counter++
movement+=0
board?.physicsBody!.applyImpulse(CGVectorMake(movement, 0))
points.text = "Points: " + String(counter)
if alive == true {
contact.bodyB.node!.removeFromParent()
alive = false
}
}
func createNewDart() {
if alive == false {
let dart = DartNode.dart(CGPoint(x: self.frame.size.width/2, y: 77))
self.addChild(dart)
alive = true
}
}
I cant exactly tell how to solve the problem but it is pretty easy to tell what is nil and shouldnt be by looking in the bottom part (just left of the error message) and browse through the variables and see which one = nil. It may be your dart or board or something unrelated. Make sure the one that is nil is initialized ie ( var dart : SKNode!) and then defined ie ( dart.physicsBody? = SKPhysicsBody(....) ) Hope this helps!

Swift: score increases twice because collision is detected twice?

I'm building a sprite kit game in swift and I need the score to increase by 1 when collision between 2 nodes is detected. The score is stored in a variable named animalsCount and is outputted to a label node:
//Score count in stats bar
//Animal score count
animalsCount = 0
animalsCountLabel.text = "\(animalsCount)"
animalsCountLabel.fontSize = 45
animalsCountLabel.fontColor = SKColor.blackColor()
animalsCountLabel.position = CGPoint (x: 630, y: 40)
addChild(animalsCountLabel)
The two sprite nodes that are colliding are savior and chicken1. Right now, I am keeping score and detecting collision using the following code:
func didBeginContact(contact: SKPhysicsContact) {
//Chicken1
if (contact.bodyA.categoryBitMask == ColliderType.Savior.rawValue && contact.bodyB.categoryBitMask == ColliderType.Chicken1.rawValue ) {
println("chicken1 contact made")
chicken1.hidden = true
chicken1.setScale(0)
animalsCount++
animalsCountLabel.text = "\(animalsCount)"
} else if (contact.bodyA.categoryBitMask == ColliderType.Chicken1.rawValue && contact.bodyB.categoryBitMask == ColliderType.Savior.rawValue) {
println("chicken1 contact made")
chicken1.hidden = true
chicken1.setScale(0)
}
Score is not increased in the else if statement because it can't happen in my game.
The problem is that animalsCount increases by 2, not 1, every time savior and chicken1 collide.
After some troubleshooting, I found out this is NOT because the score is being increased for both of the colliding bodies. This is not the case because only 1 line of code is ever satisfied. This is the only line that is satisfied:
if (contact.bodyA.categoryBitMask == ColliderType.Savior.rawValue)
The score goes up by 2 instead of 1 because savior seems to "bounce" off of chicken1 so that contact.bodyA.categoryBitMask is set equal to ColliderType.Savior.rawValue TWICE every time collision appears to occur ONCE.
I don't know how to fix this problem. How do I make it so that collision is only detected ONCE and so the score is only increased once?
I eventually solved the problem using an Int variable that controlled if statements so collision could only be detected once until the sprite node cycled through and the variable was reset.
I declared a variable called chickenHasBeenGrabbed and set it at 0 initially. Once collision had been detected that first time, I set chickenHasBeenGrabbed to 1. Only after chickenHasBeenGrabbed was set back to 0 could collision be detected again:
func didBeginContact(contact: SKPhysicsContact) {
//Chicken1
if chickenHasBeenGrabbed == 0 {
if (contact.bodyA.categoryBitMask == ColliderType.Savior.rawValue && contact.bodyB.categoryBitMask == ColliderType.Chicken1.rawValue ) {
println("chicken1 contact made")
chicken1.hidden = true
chicken1.setScale(0)
animalsCount += 1
animalsCountLabel.text = "\(animalsCount)"
chickenHasBeenGrabbed = 1
} else if (contact.bodyA.categoryBitMask == ColliderType.Chicken1.rawValue && contact.bodyB.categoryBitMask == ColliderType.Savior.rawValue) {
println("chicken1 contact made")
chicken1.hidden = true
chicken1.setScale(0)
}
}
else if chickenHasBeenGrabbed == 1 {
if (contact.bodyA.categoryBitMask == ColliderType.Savior.rawValue && contact.bodyB.categoryBitMask == ColliderType.Chicken1.rawValue ) {
println("nothing to do; chicken was already grabbed!")
} else if (contact.bodyA.categoryBitMask == ColliderType.Chicken1.rawValue && contact.bodyB.categoryBitMask == ColliderType.Savior.rawValue) {
println("nothing to do; chicken was already grabbed!")
}}