Joyful Games – iPhone game development with Apple’s Swift new language

Email Contact

Play SnakeJoy! The most addicting fun snake game on the internet

Play SnakeJoy in Your Browser!

Upside Down SKPhysicsBody when Loaded From Texture

I ran into an odd SpriteKit bug the other day when preloading and caching my texture atlases. It seems that you cannot create more than one SKPhysicsBody from a single instance of a texture, or all subsequent physics bodies will be created upside down. This StackOverflow thread suggests it’s an issue with internally cached textures.

Building an SKPhysicsBody from a cached texture creates inverted physics bodies

Building an SKPhysicsBody from a cached texture creates inverted physics bodies

It may be possible to avoid this by creating a new instance of your texture atlas in memory each time you need to create a physics body from a texture. I don’t want to do this, so I decided to draw a path for my penguin’s physics body instead:

let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 12, 21)
CGPathAddLineToPoint(path, nil, -27, -3)
CGPathAddLineToPoint(path, nil, -12, -16)
CGPathAddLineToPoint(path, nil, 24, 8)
CGPathCloseSubpath(path)
self.physicsBody = SKPhysicsBody(polygonFromPath: path)

This gives a passable result. It’s too bad that the texture based physics body suffers from this bug, since it’s otherwise so useful. Perhaps it will be fixed in Swift 2.

Using a CGPath to create a reasonably accurate physics body

Using a CGPath to create a reasonably accurate physics body