在LibGDX中使用Sprite类进行动画处理

时间:2018-01-20 02:04:58

标签: java animation libgdx sprite

我在LibGDX中制作了一款简单的游戏。我想为我的主播放器使用Sprite类方法,同时使用Animation类来为播放器设置动画。我已经让动画工作,我只是无法将它与Sprite类集成。

这是我的代码:

package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Array;

public class Game extends ApplicationAdapter {
    SpriteBatch batch;

    private TextureAtlas runAtlas;
    private Animation runAnimation;

    private TextureAtlas idleAtlas;
    private Animation idleAnimation;

    private TextureRegion currentIdleFrame;

    private Sprite player;

    private float elapsedTime = 0;
    private float playerX = 10;
    private float playerY = 10;


    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void create () {
        batch = new SpriteBatch();

        runAtlas = new TextureAtlas(Gdx.files.internal("runSpritesheet.atlas"));
        runAnimation = new Animation(1/12f, runAtlas.getRegions());

        idleAtlas = new TextureAtlas(Gdx.files.internal("idleSpritesheet.atlas"));
        idleAnimation = new Animation(1/3f, idleAtlas.getRegions());

        player = new Sprite();

    }

    @Override
    public void render () {
        currentIdleFrame = (TextureRegion) idleAnimation.getKeyFrame(elapsedTime, true);
        elapsedTime += Gdx.graphics.getDeltaTime();

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();

        if(Gdx.input.isKeyPressed(Keys.DPAD_RIGHT)) {
            batch.draw((TextureRegion) runAnimation.getKeyFrame(elapsedTime, true), playerX, playerY);
        } else if (Gdx.input.isKeyPressed(Keys.DPAD_LEFT)) {
            batch.draw((TextureRegion) runAnimation.getKeyFrame(elapsedTime, true), playerX, playerY);
        } else {
            player.setRegion(currentIdleFrame);
            player.draw(batch);
        }

        batch.end();
    }

    @Override
    public void dispose () {
        batch.dispose();
        runAtlas.dispose();
        idleAtlas.dispose();
    }
}

重点是“else”语句中播放器的空闲动画。我尝试将播放器精灵区域设置为空闲动画精灵表的当前关键帧。但是,当我启动游戏时,没有带有空闲动画的精灵出现。我也没有任何错误。我希望有人知道如何解决这个问题。谢谢你的阅读。

0 个答案:

没有答案