SpriteKit. Switching from optional to forced decompression disables the application

Im after a tutorial for SpriteKit that has a problem with the IF statement. The logic of the line is as follows: If a bullet and an asteroid collide, 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 playback area before it can disconnect. To do this, the author adds the following:

body2.node?.position.y < self.size.height

Executing the full 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, this line works with Swift 2, however Swift 3 does the correction by changing the position with the option, and the force unfolds the position.

    if body1.categoryBitMask == PhysicsCategories.bullet && body2.categoryBitMask == PhysicsCategories.asteroid && body2.node!.position.y < self.size.height {
        // remove bullet and asteroid        
    }

By the force deploying the position, the application falls "I THINK" when the three bodies collide. It is really hard to say when viewing the screen.

, . , , , ? , , body2.node , , , .

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
    }           
  }           
}

, , , , IF?

+4
2

, if != nil ( ) , .

if let 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
        }           
    }           
}

, ! nil , .

+5

nathan , guard , :

...

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
    }           

}

, , , node, , , , w631 > .

, , node, .

+4

Source: https://habr.com/ru/post/1665654/


All Articles