Some useful SKPhysicsBody Extensions for SpriteKit nodes

by Lou Franco

Each node we create in the scene can optionally have a physicsBody associated with it. If it does, then it will have velocity and acceleration and forces, like collisions and gravity, will have an effect on them.

If we don't want that (for example with label nodes that show the score), we just need to keep the physics body nil, which is its default.

There are some common patterns, so it's useful to extend SKPhysicsBody. Here are two functions that are meant to be used when you create a physics body.

ideal() makes the object an ideal physics object without friction, drag, or energy losses.

manualMovement() makes the object not affected by forces, but otherwise participates in the simulation (via collisions). This is useful for walls.

extension SKPhysicsBody {
  /// Makes the physics body an ideal object without friction or drag
  /// or energy losses due to collisions
  /// - returns: self, but with body set up to be ideal. Useful for chaining.
  func ideal() -> SKPhysicsBody {
    self.friction = 0
    self.linearDamping = 0
    self.angularDamping = 0
    self.restitution = 1
    return self
  }

  /// Makes the physics body ignore forces, but still participate in
  /// collisions. Useful for walls. You can still manually move it
  /// in your update function or in response to taps.
  /// - returns: self, but with body set up to be manually moved. Useful for chaining.
  func manualMovement() -> SKPhysicsBody {
    self.isDynamic = false
    self.allowsRotation = false
    self.affectedByGravity = false
    return self
  }
}

You would use it like this for an ideal ball:

let ball = SKShapeNode(circleOfRadius: ballRadius)
ball.physicsBody =
  SKPhysicsBody(circleOfRadius: ballRadius)
   .ideal()

And like this for a wall that was both ideal and manual.

let wall = SKShapeNode(rectOf: wallSize)
wall.physicsBody =
  SKPhysicsBody(rectangleOf: wallSize)
  .ideal()
  .manualMovement()

Next Article: Some useful CGVector Extensions for SpriteKit

Never miss an article

Get more articles like this in your inbox.