如何在melonJS中随时间改变精灵的颜色

How to change color of a sprite over time in melonJS

本文关键字:改变 精灵 颜色 时间 melonJS      更新时间:2023-09-26

我想为移动对象添加一些会随着时间的推移而褪色的跟踪效果。这是我到目前为止得到的:

game.Trail = me.Entity.extend({
  init:function (x, y, settings)
  {
    this._super(me.Entity, 'init', [
      x, y,
      {
        image: "ball",
        width: 32,
        height: 32
      }
    ]);
    (new me.Tween(this.renderable))
    .to({
        alpha : 0,
    }, 5000)
    .onComplete((function () {
        me.game.world.removeChild(this);
    }).bind(this))
    .start();
  },
  update : function (dt) {
    this.body.update(dt);
    return (this._super(me.Entity, 'update', [dt]) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
  }
});

演示(使用 WASD 或箭头键移动)

这是要在本地测试的完整项目的链接。

但我想以与淡入淡出相同的方式更改轨迹中项目的颜色。

在相位器中,可以对精灵进行着色,但我不知道如何在 melonjs 上实现这一点。

注意:如果效果可以用基本形状而不是图像来完成,那也可以。

使用 melonJS 画布渲染器,您必须通过在精灵或可渲染对象上覆盖 draw 方法来添加着色。CanvasRenderingContext2D API有一些有用的实用程序,用于执行RGBA填充等,可以对目标画布进行着色。由于"着色"没有内置在melonJS中,因此您需要保留一个临时的画布上下文来非破坏性地着色您的精灵。

最小示例(非破坏性,但不能很好地处理透明度):

draw : function (renderer) {
    renderer.save();
    // Call superclass draw method
    this._super(me.Entity, "draw", [ renderer ]); // XXX: Assumes you are extending me.Entity
    // Set the tint color to semi-transparent red
    renderer.setColor("rgba(255, 0, 0, 0.5)");
    // Fill the destination rect
    renderer.fillRect(this.pos.x, this.pos.y, this.width, this.height);
    renderer.restore();
}

一个更复杂的选项是使用 CanvasRenderingContext2D API 创建临时画布上下文;将原始精灵复制到纹理中,在尊重透明度的同时应用色调,如有必要,请使用剪辑。


在melonJS WebGL渲染器中,您只需要在绘制之前更改全局渲染器颜色的值,并在绘制之后恢复原始值即可。最小示例:

draw : function (renderer) {
    renderer.save();
    // Set the tint color to semi-transparent red
    renderer.setColor("rgba(255, 128, 128, 1)");
    // Call superclass draw method
    this._super(me.Entity, "draw", [ renderer ]); // XXX: Assumes you are extending me.Entity
    renderer.restore();
}

这在 WebGL 中有效,因为着色器已经设置为将源图像乘以全局颜色值。你会从上面的 CanvasRenderer 选项中获得不同的颜色结果,因为 WebGL 对预乘 alpha 最满意。(在此示例中,源图像中蓝色和绿色组件的值将减少一半,从而使子画面看起来更红。

随意玩一下,但总的来说,你会更好地控制WebGL中的渲染,事实上,如果你需要做非常疯狂的效果,你可以选择自定义合成器和着色器。