How to use Bitmap font as scene 2d actor?

牧云@^-^@ 提交于 2019-12-05 08:13:49

问题


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 scene2d actor.


回答1:


Take a look at the Label class, particularly the constructor that takes a CharSequence and a LabelStyle. When you initialize your LabelStyle you can supply a BitmapFont.

Please note, if you'd like to scale or rotate the label you'll need to wrap it in a Container or add it to Table with setTransform() enabled. (This flushes the SpriteBatch so use it wisely.)




回答2:


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));


来源:https://stackoverflow.com/questions/34996693/how-to-use-bitmap-font-as-scene-2d-actor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!