SpriteKit: physics body "alpha" shape issues
08:12 29 Jun 2019

I am working with my son on a basic game based on the book Dive Into SpriteKi by Paul Hudson.

Following the book, we created a sprite for a space ship and a space junk satellite. It works, but we notice that sometimes ship goes through the junk. We tried to add sprites with the scene editor and turned on the physics:

picture showing the issues with physics body shapes

Remarkably the ship node added using scene editor have completely wrong physical body outline generated, but doing

player.physicsBody = SKPhysicsBody(texture: player.texture!, size: player.size)

does fix it. On the other hand, doing the same for the junk satellite sprite always produce the same convoluted physical body.

My only guess is there is something wrong with how (or when) the texture loaded and analyzed. It would explain why doing it repeatedly fixes the rocket ship... but what is wrong with the satellite? And how to make sure texture is properly prepared so that alpha mask for physics body works reliably?

I will appreciate any advice on how to deal with this issue (-s).

I tried to use alphaThreshold: and it makes some difference for the ship outline, but seems to have no effect for the satellite outline.

I tried to re-draw the satellite texture from scratch to rule-out an issue with original file from the book. With a completely new file of similar shape the issue is exactly the same.

We also tested iOS 12 and iOS 13 with the same results. The "canonical" code from the book have the same exactly issue.

Please see our game complete implementation on GitHub.

A fast way to reproduce the issue out of our game:

  1. Create new project in Xcode with Game template
  2. Add the satellite asset to the assets catalog:

satellite

  1. Add Color Sprite to the GameScene.sks, choose satellite for texture, and set body type to "Alpha mask" in Physics definition section.

The outcome in our case looks like this:

enter image description here

Expected outcome is an accurate outline of the sprite.

sprite-kit collision-detection