2016-02-01 32 views
2

在LibGDX中,我为我的角色制作了一个基于精灵的动画。我有一个TextureRegion为当前帧,每次我绘制精灵我想改变精灵的纹理到当前帧。这是我现在的代码。如何将TextureRegion转换为纹理来设置精灵纹理

TextureRegion currentFrame; 
Sprite sprite; 

这:

@Override 
public void draw(SpriteBatch batch) { 
    if (batch.isDrawing()) { 
     sprite.setTexture(currentFrame); <-- This line 
    } 
} 

,但是,“这一行”我得到一个错误,说我不能精灵的纹理设置为纹理区域,所以我想我需要做的是将TextureRegion转换为纹理,以便我可以将精灵设置为它。我将如何做到这一点?

回答

2

好吧,我想这getTexture()从TextureRegion类方法是不是你在这种情况下所需要的(否则你可以简单地使用它像sprite.setTexture(currentFrame.getTexture());

因为你正在做一个动画,我可能会猜测资产中存在精灵图表图像。因此,动态显示板,你应该创建一个libgdx动画,如:

int ROW = 4; // rows of sprite sheet image 
    int COLUMN = 4; 
    TextureRegion[][] tmp = TextureRegion.split(playerTexture, playerTexture.getWidth()/COLUMN, playerTexture.getHeight()/ROW); 
    TextureRegion[] frames = new TextureRegion[ROW * COLUMN]; 
    int elementIndex = 0; 
    for (int i = 0; i < ROW; i++) { 
     for (int j = 0; j < COLUMN; j++) { 
      frames[elementIndex++] = tmp[i][j]; 
     } 
    } 
    Animation playerAnimation = new Animation(1, frames); 

其中playerTexture是精灵表单图像

然后在你的性格类创建TextureRegion设置currentFrame场初始化动画的当前帧( playerAnimation以上):

// used for currentFrame initialization 
TextureRegion currentFrame = playerAnimation.getKeyFrame(0); 

然后在游戏画面的更新方法使用浮法增量(或Gdx.graphics.getDeltaTime())来更新动画的关键帧(换言之,以动画子画面)。

public void update(float delta){ 
    currentFrame = playerAnimation.getKeyFrame(delta); 
} 

终于在您的平局(或渲染)方法你画炭像

public void draw(){ 
    batch.begin(); 
    batch.draw(char.getCurrentFrame(), char.getPosition().x, char.getPosition().y); 
    batch.end(); 
} 

希望我理解你的问题正确和帮助。

+0

从技术上讲,这并不回答这个问题,但它适用于我所需要的,甚至比我目前所做的更好,因此我将其作为答案进行了upvoting并将其作为答案! –

2

为什么不使用setRegion(.......)?

sprite.setRegion(currentFrame);