Swift Game Development(Third Edition)
上QQ阅读APP看书,第一时间看更新

Physics bodies and gravity

SpriteKit simulates physics with physics bodies. We attach physics bodies to all the nodes that need physics computations. We will set up a quick example before exploring all of the details.

Dropping like flies

Our bees need to be part of the physics simulation, so we will add physics bodies to their nodes. Open your Bee.swift file and locate the init function. Add the following code at the bottom of the function:

// Attach a physics body, shaped like a circle 
// and sized roughly to our bee. 
self.physicsBody = SKPhysicsBody(circleOfRadius: size.width / 2) 

It is that easy to add a node to the physics simulation. Run the project. You will see our two bee instances drop off the screen. They are now subject to gravity, which is on by default.

Solidifying the ground

We want the ground to catch falling game objects. We can give the ground its own physics body so that the physics simulation can stop the bees from falling through it. Open your Ground.swift file, locate the createChildren function, and add this code at the bottom of the function:

// Draw an edge physics body along the top of the ground node. 
// Note: physics body positions are relative to their nodes. 
// The top left of the node is X: 0, Y: 0, given our anchor point. 
// The top right of the node is X: size.width, Y: 0 
let pointTopLeft = CGPoint(x: 0, y: 0) 
let pointTopRight = CGPoint(x: size.width, y: 0) 
self.physicsBody = SKPhysicsBody(edgeFrom: pointTopLeft, 
    to: pointTopRight) 

Run the project. The bees will now quickly drop and then stop once they collide with the ground. After the bees have landed, your simulator will look like the following screenshot:

Solidifying the ground

Note

Checkpoint 3-A

The code up to this point is available in this chapter's code resources.