Animate an SKSpriteNode with textures that have a size different from the original

牧云@^-^@ 提交于 2019-12-19 10:56:11

问题


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:


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)

  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.



来源:https://stackoverflow.com/questions/37579768/animate-an-skspritenode-with-textures-that-have-a-size-different-from-the-origin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!