How to use Bitmap font as scene 2d actor?

后端 未结 2 939
日久生厌
日久生厌 2021-02-11 11:26

I am developing a game using libgdx framework. How can i achieve scene2d action on bitmap font object ? so that i can write some text like score,message and run action like scen

2条回答
  •  独厮守ぢ
    2021-02-11 12:22

    you can extend actor class to achieve the same.

    like:-

    import com.badlogic.gdx.graphics.Color;
    import com.badlogic.gdx.graphics.g2d.Batch;
    import com.badlogic.gdx.graphics.g2d.BitmapFontCache;
    import com.badlogic.gdx.graphics.g2d.GlyphLayout;
    import com.badlogic.gdx.math.Matrix4;
    import com.badlogic.gdx.scenes.scene2d.Actor;
    
    public class FontActor extends Actor 
    {
      private Matrix4 matrix = new Matrix4();
      private BitmapFontCache bitmapFontCache;
      private GlyphLayout glplayout;
    
      public FontActor(float posX, float posY, String fontText) 
      {
      BitmapFont  fnt=new BitmapFont(Gdx.files.internal("time_newexport.fnt"),
                       Gdx.files.internal("time_ne-export.png"),false);
    
        bitmapFontCache = new BitmapFontCache(fnt);
        glplayout=bitmapFontCache.setText(fontText, 0, 0);
    
        setPosition(posX, posY);    
        setOrigin(glplayout.width / 2, -glplayout.height/2);
    }
    
      @Override
       public void draw(Batch batch, float alpha)
       {
         Color color = getColor();
         bitmapFontCache.setColor(color.r, color.g, color.b, color.a*alpha);
         matrix.idt();
         matrix.translate(getX(), getY(), 0);
         matrix.rotate(0, 0, 1, getRotation());
         matrix.scale(getScaleX(), getScaleY(), 1);
         matrix.translate(-getOriginX(), -getOriginY(), 0);
         batch.setTransformMatrix(matrix);
         bitmapFontCache.draw(batch);
    
        }
    
    
      public void setAlpha(int a)
      {
        Color color = getColor();
        setColor(color.r, color.g, color.b, a);
      }
    
      public void setText(String newFontText)
       {
         glplayout = bitmapFontCache.setText(newFontText, 0, 0);
         setOrigin(glplayout.width / 2, -glplayout.height/2);
    
         }
    
    }
    

    and you can use it like.

     Actor actor=new FontActor(20,30,"test");
     stage.addActor(actor);
     actor.addAction(Actions.moveTo(10,10,1));
    

提交回复
热议问题