Rebooking a sprite with xScale in SpriteKit in iOS 8 does not flip SKPhysicsBody

I have a setting where there is an empty SKSpriteNode

("Player") that has the number N SKSpriteNode

as children (body parts like "Hand"). Each child has SKPhysicsBody

, created as follows:

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

      

When I try to flip the whole sprite ("Player") with

self.xScale = -1

      

all textures are flipped correctly, but SKPhysicsBody

not affected. How to flip the whole sprite with all the children and them SKPhysicsBody

correctly?

+3


source to share


2 answers


One way to create a physical object from a texture that is flipped horizontally is to create an inverted version of the input image using image editing software such as Photoshop. An alternative way is to flip the original image using the main graphics. Here's an example of how to do it:



func flippedTextureWithImageNamed(name:NSString) -> SKTexture
{
    let image = UIImage(named:name)

    UIGraphicsBeginImageContext(image.size);
    let context = UIGraphicsGetCurrentContext()

    CGContextTranslateCTM(context, image.size.width, image.size.height)
    CGContextScaleCTM(context, -1.0, -1.0)

    CGContextDrawImage(context, CGRectMake(0.0, 0.0, image.size.width, image.size.height), image.CGImage)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext();

    return SKTexture(image: newImage)
}

      

+3


source


Scale is a visual property and does not affect physics. To change the shape of a node, you can create and assign a new body with a new shape.



+2


source







All Articles