You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LibGDX中draw方法内如何将Object转换为Texture?

LibGDX中draw方法内如何将Object转换为Texture?

嘿,这个问题我之前升级LibGDX版本的时候也碰到过!其实根源出在新版LibGDX对Animation类的泛型改动上——旧版本的Animation是无泛型的,而新版本它变成了泛型类,你现在的声明没指定具体类型,导致getKeyFrame()返回的是Object,但SpriteBatch.draw()需要的是Texture或者TextureRegion类型,自然就报错了。

解决方法很简单,分两步来:

  1. 修正Animation的泛型声明
    把你的Animation变量声明改成带泛型的,一般动画帧用TextureRegion(适配精灵图,更灵活),所以改成:

    private Animation<TextureRegion> standLeftAnime, standRightAnime;
    

    如果你的动画帧是单张Texture,也可以指定Animation<Texture>,不过TextureRegion是更常用的选择。

  2. 确保初始化Animation时传入对应类型的帧
    初始化动画的时候,要传入TextureRegion数组(比如从精灵图集或者切割Texture得到),举个简单的例子:

    // 假设你已经加载了左站立的纹理帧
    TextureRegion[] standLeftFrames = new TextureRegion[3];
    standLeftFrames[0] = new TextureRegion(yourTexture, 0, 0, 64, 64);
    standLeftFrames[1] = new TextureRegion(yourTexture, 64, 0, 64, 64);
    standLeftFrames[2] = new TextureRegion(yourTexture, 128, 0, 64, 64);
    
    // 创建动画,0.1f是每帧的间隔时间
    standLeftAnime = new Animation<>(0.1f, standLeftFrames);
    

做完这两步,standLeftAnime.getKeyFrame(runTime)就会返回TextureRegion类型,而SpriteBatch正好有对应的draw(TextureRegion, float, float, float, float)重载方法,你原来的draw调用就完全可以正常运行了,不会再报类型不匹配的错误。

另外小提醒:别忘在render()方法里正确更新runTime哦,比如:

float deltaTime = Gdx.graphics.getDeltaTime();
runTime += deltaTime;

备注:内容来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 07:05:31