Kie*_*k93 4 java scaling animation sprite libgdx
另一天,另一个问题。
我正在尝试从 TextureRegions 制作动画,但我需要按某个值对其进行缩放。我在缩放静止图像(由纹理区域制成的精灵)方面没有问题,但是,我不知道为什么,它不适用于动画帧。
对于静止图像,我会做类似的事情:
    darknessActive = new Sprite(AssetLoaderUI.darknessActive);
    darknessActive.setPosition(50, 20);
    darknessActive.setScale(scaler);
Run Code Online (Sandbox Code Playgroud)
然后我在渲染器中渲染它就好了。
通过动画,我尝试做这样的事情:
    Frame1 = new TextureRegion(texture, 764, 75, 141, -74);
    Frame2 = new TextureRegion(texture, 907, 75, 133, -75);
    Frame1S = new Sprite(Frame1);
    Frame1S.setScale(scaler);
    Frame2S = new Sprite(Frame2);
    Frame2S.setScale(scaler);
    Sprite[] Frames = { Frame1S, Frame2S };
    myAnimation = new Animation(0.06f, Frames);
    myAnimation.setPlayMode(Animation.PlayMode.LOOP);
Run Code Online (Sandbox Code Playgroud)
但图像仍为原始尺寸,“缩放器”没有任何区别。
2018 编辑:在较新版本的 LibGDX 中,动画类不限于 TextureRegions。它可以为任何通用对象数组设置动画,因此您可以创建一个Animation<Sprite>,尽管您需要确保每次获得关键帧精灵时都应用了适当的比例。就我个人而言,我认为应该避免使用 Sprite 类,因为它将资源(图像)与游戏状态混为一谈。
你没有说你是如何绘制动画的,但大概你正在使用一种不知道精灵比例的方法。
由于 Animation 类存储 TextureRegions,如果您从动画中获取一帧来绘制如下:
spriteBatch.draw(animation.getKeyFrame(time), x, y);
Run Code Online (Sandbox Code Playgroud)
那么精灵批处理不知道它是一个精灵的实例,只知道它是一个 TextureRegion 的实例,它不包括缩放信息。
一种快速而肮脏的方法是这样的:
Sprite sprite = (Sprite)animation.getKeyFrame(time));
spriteBatch.draw(sprite, x, y, 0, 0, sprite.width, sprite.height, sprite.scaleX, sprite.scaleY, 0);
Run Code Online (Sandbox Code Playgroud)
但是如果你想要一个行为有点像精灵的动画,你可以将它子类化,让它存储缩放数据(如果你喜欢,旋转和位置)并绘制自己。然后您根本不必担心 Sprite 实例。
例如:
public class SpriteAnimation extends Animation {
    float scaleX = 1;
    float scaleY = 1;
    /*...duplicate and call through to super constructors here...*/
    public void setScaling(float scale){
        scaleX = scale;
        scaleY = scale;
    }
    public void draw (float stateTime, Batch batch, float x, float y) {
        TextureRegion region = getKeyFrame(stateTime);
        batch.draw(region, x, y, region.width*scaleX, region.height*scaleY);
    }
}
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您可以自定义它来存储 x 和 y、旋转、原点等,就像精灵一样。创建它时,您根本不会使用 Sprite 类。你会做这样的事情。
frame1 = new TextureRegion(texture, 764, 75, 141, -74);
frame2 = new TextureRegion(texture, 907, 75, 133, -75);
TextureRegion[] frames = { frame1, frame2 };
mySpriteAnimation = new SpriteAnimation(0.06f, frames);
mySpriteAnimation.setScaling(scaler);
mySpriteAnimation.setPlayMode(Animation.PlayMode.LOOP);
Run Code Online (Sandbox Code Playgroud)