2

我想为移动的物体添加一些轨迹效果,随着时间的推移会逐渐消失。这是我到目前为止所得到的:

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 上实现这一点。

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

4

1 回答 1

2

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

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

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 中对渲染有更多的控制,事实上,如果你需要做非常疯狂的效果,你可以选择自定义合成器和着色器。

于 2016-07-15T23:05:27.273 回答