(LibGDX) 改变演员的颜色

(LibGDX) Changing Color of Actor

所以,我有一个扩展 Actor 的 class,我正在尝试更改它的 alpha 值; objectPreview 是 class:

的一种
@Override
public void display() {

    ...

    // remove previous object preview from stage
    objectPreview.remove();

    ... 

    // add a translucent preview of where the object will be added
    objectPreview.getColor().a = 0.5f;
    stage.addActor(objectPreview);

    ...

    stage.draw();
}

这是我的 draw 自定义方法 Actor:

@Override
public void draw(Batch batch, float alpha) {
    batch.enableBlending();
    batch.draw(texture, pos.x, pos.y);
}

每帧都会调用display方法,objectPreviewstage添加的Actor

但是,修改objectPreview的alpha值不起作用。

否则,这会按预期工作,在屏幕上放置 Actor 的预览并在每一帧清除/重绘它。

我也试过setColor()方法,还是不行。即使我改变了 r、g、b 值,也没有任何反应;该对象仍然是原始的 Actor's 纹理。

为什么演员的 Color 没变?

当您子class Actor 时,您可以在draw 方法中应用它自己的颜色。我不确定他们为什么不将此构建到 Actor class 中,除了可能有很多可能使用颜色的方式,或者因为某些 Actor 没有任何与之关联的视觉效果,所以上色会浪费时间。

首先,请注意传递给 draw 方法的第二个参数是 parentAlpha,而不是您标记的 alpha。这是因为父项的 alpha 应乘以子项的 alpha 以获得适当的淡入淡出效果。

所以您更新后的 draw 方法应该如下所示:

@Override
public void draw(Batch batch, float parentAlpha) {
    batch.enableBlending(); //You can probably remove this line*
    Color color = getColor(); //keep reference to avoid multiple method calls
    batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
    batch.draw(texture, pos.x, pos.y);
}

/*    * It would only be useful if you have some custom Actors that disable blending. 
I don't think any of the built-in actors disable blending. Since many actors will 
require blending, it is usually best to leave it on even for fully opaque sprites, in 
order to avoid ending up with many draw calls. */

另请注意,如果您想利用 Actor 已经存在的 scaleXscaleY 字段,您也可以相应地修改 draw 方法以使用他们。