移动Phaser.Graphics线的一端

时间:2016-01-25 21:27:01

标签: phaser-framework

对于一个项目,我试图在Phaser中绘制一条移动线。我最初使用game.debug.geom(line)绘制它,但这不是真正正确的方法,因为它不允许样式化,并且因为调试器会降低性能。

阅读文档,在我看来,这样做的方法是使用Phaser.Graphics对象,但我还没有能够让它工作。举个例子,我尝试将一条线移动作为时钟之手,一端固定,另一端移动。

我认为可以在中间创建Graphics对象,然后在update中使用reset清除它并将其带回中心,然后{{ 3}}制作其余部分。但相反,我得到的是一条从中心向外流出的线,然后是一条戒指。

悲伤的照片:

lineTo

我尝试了What I have。代码在下面重复。我想要的是一条线(线?)从圆心到圆周点。

Graphics对象是最好的方法吗?我该怎么做?

Demo.prototype = {
  create: function() {
    this.graphics = game.add.graphics(
      game.world.centerX,
      game.world.centerY
    );
    this.graphics.lineStyle(2, 0xffd900);
    this.counter = 0;
    this.step    = Math.PI * 2 / 360;
    this.radius  = 80;
  },
  update: function() {
    this.graphics.reset(
      this.game.world.centerX,
      this.game.world.centerY
    );
    var y = this.radius * Math.sin(this.counter);
    var x = this.radius * Math.cos(this.counter);
    this.graphics.lineTo(x, y);
    this.counter += this.step;
  }
};

2 个答案:

答案 0 :(得分:1)

你可能想查看这款名为Cut It的Phaser游戏(不是我的游戏顺便说一句,找到它here)。

它还通过巧妙地使用Phaser.TileSprite绘制可变长度的虚线,然后更改其宽度。

TileSprite绘制一个重复的图案,你可以使用它来绘制一条线条,通过绘制一个线段的一个位图,使用它作为TileSprite的背景,并使TileSprite的高度与高度相同位图。

您可以查看游戏的源代码,它已经过压缩和缩小,但仍然有些可读。您可以查找名为cut_line的变量。

答案 1 :(得分:1)

我终于明白Phaser.Graphics对象所采用的坐标是局部的,分别对应于对象的内部坐标系。使用moveTo(0, 0)具有将对象的绘图指针移回其原点所需的结果(而不是像我最初想的那样,将其移动到游戏世界的原点)。另一方面,使用reset(0, 0)会将对象的原点移动到世界的原点。

至于删除前面的行,我发现的唯一方法是手动清除对象的graphicsData数组(没有调用destroy()并创建一个全新的对象,这可能不是非常好的主意)。

用这个替换原始问题中的代码就可以了:

Demo.prototype =  {
  create: function() {
    this.graphics = game.add.graphics(
      game.world.centerX,
      game.world.centerY
    );
    this.graphics.lineStyle(2, 0xffd900);
    this.counter = 0;
    this.step    = Math.PI * 2 / 360;
    this.radius  = 80;
  },
  update: function(){
    // Erases the previous lines
    this.graphics.graphicsData = [];

    // Move back to the object's origin
    // Coordinates are local!
    this.graphics.moveTo( 0, 0 );

    var y = this.radius * Math.sin(this.counter);
    var x = this.radius * Math.cos(this.counter);
    this.graphics.lineTo(x, y);
    this.counter += this.step;
  }
};