Animate an SKSpriteNode with textures that have a

2019-02-20 07:19发布

I want to animate an SKSpriteNode using textures from an SKTextureAtlas, using SKAction.animateWithTextures(textures,timePerFrame,resize,restore). However, the textures in the atlas have a size that is slightly larger than the original texture (it's basically a character moving). When the action is run, the textures are either compressed to fit the original size of the sprite, or recentered when I set resize to false, which changes the position of the character. What I want, though, is for the textures to be anchored at the lower-left corner (or lower-right, depending on the direction) so that the position of the character doesn't change apart from the extra part of the texture.

I've tried changing the anchor point of the sprite prior to running the action, but obviously that applies to the original texture as well. Also, I guess changing the size of the original texture would have an impact on the physics behaviour, which I want to avoid.

Does anyone have a suggestion about how to do this?

Thanks!

David

1条回答
成全新的幸福
2楼-- · 2019-02-20 07:46

This would work

  1. Edit all the textures to match the size of the largest sized texture.

Just give the smaller textures some padding using an alpha channel to give you a transparent background.

E.g. Notice how the first texture has lots of negative space (From CartoonSmart.com)

enter image description here

  1. Create the physics body with a certain size in mind. E.g. You can load the texture without the padding and get the size. Then position it as needed onto the new and improved texture with padding. So after you create the Sprite as normal with the new resized textures you can then

    /// load a texture to be a template for the size
    let imageTextureSizeTemplate = SKTexture(imageNamed: textureWithoutPadding)
    
    let bodySize = imageTextureSizeTemplate.size()
    
     /// position template texture physics body on texture that will be used  
    let bodyCenter = CGPointMake(0.5, 0.5)
    
    // create physics body
    let body:SKPhysicsBody = SKPhysicsBody(rectangleOfSize: bodySize, center: bodyCeneter)
    
        self.physicsBody = body
    
  2. Set resize: false when you animate the textures.

查看更多
登录 后发表回答