SpriteKit: using SKTextureAtlas causes an invalid physical body

I am creating my first game with a set of sprites and recently read an article that says SKTextureAtlas is used to improve performance.

So, I transferred all my sprites to organized .atlas folders and updated the code accordingly. However, now my sprites have weird physical bodies (mostly overly extended).

For example, my game sprite has three states: Flying (flat), Flying Up, and Flying Down. The three images are pretty similar, with slight variations (hands pointing to the plane, up, down).

Before switching to texture atlases, the physical body was beautiful with the image. However, now it is much larger than the image and stretches slightly along the y axis.

Here is my player.atlas file structure:

player-flying-iphone.atlas:

  • player-flying-down@2x.png
  • player-flying-down@3x.png
  • player-flying-up@2x.png
  • player-flying-up@3x.png
  • player-flying@2x.png
  • player-flying@3x.png

Here is an example of my code: (Player is a subclass of SKSpriteNode)

 let textureAtlas = SKTextureAtlas(named: "player-iphone") let playerFlyingTexture = textureAtlas.textureNamed("player-flying") let player = Player(texture: playerFlyingTexture, color: UIColor.clearColor(), size: CGSizeMake(100.0, 100.0)) let physicsBody = SKPhysicsBody(texture: playerFlyingTexture, size: CGSizeMake(100.0, 100.0)) physicsBody.dynamic = true physicsBody.affectedByGravity = true physicsBody.usesPreciseCollisionDetection = false physicsBody.categoryBitMask = CollisionCategories.Player physicsBody.contactTestBitMask = CollisionCategories.Enemy physicsBody.collisionBitMask = CollisionCategories.EdgeBody physicsBody.allowsRotation = false player.physicsBody = physicsBody 
+1
source share
3 answers

(credit to @Whirlwind for reference)

So, for me, the fix ended up having to change this:

 let physicsBody = SKPhysicsBody(texture: self.texture, size: self.size) 

.. to that..

 let physicsBody = SKPhysicsBody(texture: self.texture, alphaThreshold: 0.3, size: self.size) 

Apparently, the SKTextureAtlas cropping method used to create the physical body has problems figuring out what needs to be cropped, so setting alphaThreshold clearly helped fix it.

Obviously, this value will depend on your own image and what transparency you have. But if you have hard edges like me, you should be able to set this to some arbitrary value and be good to go.

+1
source

You adjust the texture size as follows:

CGSize(widht:100, height:100)

which, obviously, are not the correct dimensions of your texture.

Use the actual texture size instead:

yourTexture.size()

+1
source

This problem exists on iPad 3 (iOS 9.3.5 and xcode 8.1), and in my situation alphaThreshold did not solve the problem with the wrong PhysBody.

I had to switch to the Atlas of the new sprite instead of Texture Atlas, which magically fixed the problem.

0
source

Source: https://habr.com/ru/post/1260079/


All Articles