代码之家  ›  专栏  ›  技术社区  ›  witsel

精灵动画libgdx数组

  •  0
  • witsel  · 技术社区  · 2 年前

    我正在尝试为一个大学项目创建一个游戏。在主菜单中,我用以下内容设置了角色动画:

    spidey = new Texture("spidey.png");
    TextureRegion[][] tmpFrames = 
    TextureRegion.split(spidey,spidey.getWidth()/3,spidey.getHeight()/5);
    animationFrames = new TextureRegion[15];
    int index = 0;
    for (int i=0; i<5; i++){
        for (int j=0; j<3; j++){
            animationFrames[index++] = tmpFrames[i][j];
        }
    }
    animation = new Animation(0.15f, (Object[]) animationFrames);
    

    但如果我有这样一组字符:

    public void characters() {
    enemies = new Array<Enemy>();
    enemies.add(new Enemy(new Sprite(new Texture("img1.png")), spawn));
    enemies.add(new Enemy(new Sprite(new Texture("img2.png")), spawn));
    enemies.add(new Enemy(new Sprite(new Texture("img3.png")), spawn));
    enemies.add(new Enemy(new Sprite(new Texture("img4.png")), spawn));      
    }
    

    如何设置所有角色的动画?

    1 回复  |  直到 2 年前
        1
  •  0
  •   Tobias    2 年前

    要为您的敌人使用动画,您不需要创建敌人阵列,但需要 Animation 对象,就像您在问题的第一个代码段中所做的那样。

    类似这样:

    public void character() {
      TextureRegion[] enemyAnimationTextures = new TextureRegion[] {new Texture("img1.png"), new Texture("img2.png"), new Texture("img3.png"), new Texture("img4.png")};
      Animation<TextureRegion> animation = new Animation<>(0.15f, enemyAnimationTextures, PlayMode.LOOP); // use PlayMode.NORMAL if you don't want the animation to loop
      enemy = new Enemy(animation);
    }
    

    现在,您需要能够绘制动画。因此,您需要添加一个将增量时间作为参数获取的绘制方法(或者从 Gdx.graphics.getDeltaTime() ,如中所示 this tutorial (这有点过时,但仍然可以使用……):

    // in you Enemy class
    private float animationStateTime = 0f;
    private Animation<TextureRegion> animation;
    private SpriteBatch spriteBatch = new SpriteBatch();
    
    public Enemy(Animation<TextureRegion> animation) {
      this.animation = animation;
    }
    
    public void draw() {
      animationStateTime += Gdx.graphics.getDeltaTime(); // a bit outdated, but working
      
      // get the current frame of the animation for this enemy
      TextureRegion currentFrame = animation.getKeyFrame(animationStateTime);
    
      // draw the texture region (TODO this must probably be changed to not only draw the enemy at (50, 50))
      spriteBatch.begin();
      spriteBatch.draw(currentFrame, 50, 50); // Draw current frame at (50, 50)
      spriteBatch.end();
    }