Search code examples
iphoneswiftxcode6-beta6

Adjust SKSpriteNode and SKPhysicsBody with specific image.png or image.jpg


I am developing a game with a character with some particular shape, I am creating an SKSpriteNode object with this line:

let rockl:SKSpriteNode = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: newweight*ancho/16, height: alto/5))

I am assigning a physical body with this line:

rockl.physicsBody = SKPhysicsBody(rectangleOfSize: pipeBotton.size)

and I am assigning the image with this line:

rockl.texture = SKTexture(imageNamed: "character.png")
rockl.texture.filteringMode = SKTextureFilteringMode.Nearest

But the borders are not the same to the border of the image. how can I adjust the object to the image? or whats is the technique to create a custom shape?


Solution

  • You'll want to create your physicsBody with SKPhyiscsBody(texture, size). From the docs:

    Use this method when your sprite has a shape that you want replicated in its physics body. The texture is scaled to the new size and then analyzed. A new physics body is created that includes all of the texels in the texture that have a nonzero alpha value. The shape of this body attempts to strike a good balance between performance and accuracy. For example, fine details may be ignored if keeping them would cause a significant performance penalty.

    You can also create your SKSpriteNode with a texture directly instead of creating it with a flat color first:

    let rocklTexture = SKTexture(imageNamed: "character.png")
    rocklTexture.filteringMode = SKTextureFilteringMode.Nearest
    
    let rocklSize = CGSize(width: newweight*ancho/16, height: alto/5)
    
    let rockl = SKSpriteNode(texture: rocklTexture, size: rocklSize)
    rockl.physicsBody = SKPhysicsBody(texture: rocklTexture, size: rocklSize)