• 2D
  • How to get the current frame texture from an AnimatedSprite when using a sprite sheet?

Hello, I have an animatedSprite and would like to get the current animation frames texture. When using a bunch of keyframes in a folder I can do this by using:

var frame_texture = animated_sprite.get_sprite_frames().get_frame("name_of_anim", animated_sprite.get_frame())

The issue I have is when I have an animation that uses a sprite sheet, frame_texture returns the whole sprite sheet and not the current frame being displayed.

Even weirder is that the size of the frame_texture matches what a single animation frame should be, the sprite sheet is just scaled to fit within that size.

I couldn't find any documentation on this behaviour. Is there a better/correct way to get the frame texture that I can use for sprite sheets?

Thanks

Hi,

That is probably because of how sprite sheet works. I am not sure about how SpriteFrames handle frames from sprite sheet, but it looks like "get_frame" method return just texture which is sprite sheet itself and size of a single frame. In case of frames on separated images it may work, because for each frame there is unique texture to return. In case of sprite sheet actually all frames share the same texture, so each frame is described by its size and position on texture rather than texture itself, so as I understand "get_frame" method can't work in this case.

I think in case of sprite sheet better way is to use Sprite node and animate it properities by AnimationPlayer. That way you can easly calculate what is current frame. There are properities like VFrames, HFrames, Frame and Frame Coords, so if you want to apply the same frame to another Sprite you just need to copy some properities or if you need exactly part of the texture you can also calculate it like:

var spriteTexture : Texture = mySprite.texture
var textureSize : Vector2 = spriteTexture.get_size()
var frameSize : Vector2 = Vector2(textureSize.x / mySprite.hframes, textureSize.y / mySprite.vframes)
var currentFramePosition : Vector2 = Vector2(frameSize.x * mySprite.frame_coords.x, frameSize.y * mySprite.frame_coords.y)

That way you have everything you need to even render that frame "by hand" (texture, frame size and location of frame on that texture), but if you use another Sprite node in most cases it is even not necessary because you only need to copy: texture, hframes, vframes and frame to display the same frame (Sprite will do other calculations itself).

5 months later

use this to get the current texture .

texture=$AnimatedSprite.get_sprite_frames().get_frame($AnimatedSprite.animation,$AnimatedSprite.get_frame())

for the size you can simply assign a scale value using the scale property