如何使一个“手工制作”的演员淡化LibGDX

时间:2017-05-29 17:32:20

标签: java android libgdx

我正在尝试创建一个黑色矩形,在我的应用程序中执行某个操作时淡入淡出,但我似乎无法找到方法。我创建了一个新的Rectangle类,它扩展了Scene2D的Actor,它的外观如下:

public class Rectangle extends Actor{
   private Texture texture;

   public Rectangle(float x, float y, float width, float height, Color color) {
      createTexture((int)width, (int)height, color);

      setX(x);
      setY(y);
      setWidth(width);
      setHeight(height);
  }

  private void createTexture(int width, int height, Color color) {
      Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
      pixmap.setColor(color);
      pixmap.fillRectangle(0, 0, width, height);
      texture = new Texture(pixmap);
      pixmap.dispose();
  }

  @Override
  public void draw(Batch batch, float parentAlpha) {
      Color color = getColor();
      batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
      batch.draw(texture, getX(), getY(), getWidth(), getHeight());
  }
}

问题是当我绘制矩形时,我必须设置一个常量parentAlpha。如果我打电话:

rectangle.addAction(alpha(0.5f));

它不会做任何事情,因为alpha不会改变。如果没有固定的parentAlpha,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

固定的parentAlpa是什么意思?

根据您的问题,您希望fade in黑色矩形。要实现此设置的演员的alpha值为零,并在屏幕上显示时添加fadeIn()操作。

public class MultiLine extends ApplicationAdapter {

  Stage stage;

  @Override
  public void create() {

    stage=new Stage();

    RectActor rectActor=new RectActor(100,100,100,100, Color.BLACK);
    RectActor rectActor1=new RectActor(150,150,100,100, Color.BLACK);

    stage.addActor(rectActor1);
    stage.addActor(rectActor);

    rectActor.getColor().a=0;                //Make transparent
    rectActor.addAction(Actions.fadeIn(1f)); // In one second rectActor appear on Screen.
  }

  @Override
  public void render() {

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

    stage.draw();
    stage.act();
  }

  @Override
  public void dispose() {
      stage.dispose();
  }
}

Rectangle已经在API中,因此最好使用不同的名称。

public class RectActor extends Actor {

    private Texture texture;

    public RectActor(float x, float y, float width, float height, Color color) {
        createTexture((int)width, (int)height, color);

        setX(x);
        setY(y);
        setWidth(width);
        setHeight(height);
    }

    private void createTexture(int width, int height, Color color) {
        Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
        pixmap.setColor(color);
        pixmap.fillRectangle(0, 0, width, height);
        texture = new Texture(pixmap);  //creating texture for each RectActor is not profitable so create once and share in all RectActor
        pixmap.dispose();
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        Color color = getColor();
        batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
        batch.draw(texture, getX(), getY(), getWidth(), getHeight());
    }
}