Game development for Apple platforms

Solving the concave polygon collision problem for pieces

In the previous post on spawning pieces I mentioned I ran into a problem with the collision paths.

The problem

When initializing an SKPhysicsBody from a CGPath, SpriteKit does not support concave polygons. So our L-piece - despite the debug rendering showing a correct outline - had an incorrect shape for collision purposes.

A visual reminder of the problem:

The solution

I revisited how the LPiece node is initialized, and instead of creating a CGPath polygon, I created the body using this initializer:

init(bodies: [SKPhysicsBody])

As arguments I pass two rectangle-shaped bodies. One for the leftmost side of the L-shape (a 1x3 rectrangle) and one for the bottom-right part (a 1x1 rectangle):

// create left and right sides separately, as rectangles with an offset from center
let gridSize = 30
let leftBody = SKPhysicsBody(rectangleOf: leftSize, center: CGPoint(x: -gridSize/2, y: 0))
let rightBody = SKPhysicsBody(rectangleOf: rightSize, center: CGPoint(x: gridSize/2, y: -gridSize))

// the combined body acts as a concave polygon with regards to collision boundaries
let body = SKPhysicsBody(bodies: [leftBody, rightBody])

The end result

Notice that the L pieces can now be correctly stacked together, and when they're being rotated, there are no invisible-but-colliding parts.

#physics #spritekit