swiftsprite-kitsprite-sheetsktexture

SKTexture in:texture yields empty result


I was trying to cut a sprite sheet and for some reason beyond me the result was always empty.

One would think that the below would give you half the down-left quarter of the image.

let allTex = SKTexture(imageNamed: "zelda")
let standTex = SKTexture(rect: CGRect(x: 0, y:0, width: 1/2, height: 1/2), in: allTex)

This however gives empty results.


Solution

  • The problem was that CGRect was using the wrong initializer. One would think that the below would give you half the down-left quarter of the image.

    let allTex = SKTexture(imageNamed: "zelda")
    let standTex = SKTexture(rect: CGRect(x: 0, y:0, width: 1/2, height: 1/2), in: allTex)
    

    This however gives empty results due to the type inference saying the results should be an int followed by some unfortunate rounding of 1/2 being 0. To fix this do this instead:

    let allTex = SKTexture(imageNamed: "zelda")
    let standTex = SKTexture(rect: CGRect(x: 0, y:0, width: 1.0/2.0, height: 1.0/2.0), in: allTex)
    

    This forces the calculation results to be a double 0.5 and then eventually using CGRect with accurate float instead of rounded int.