如何在js加速乒乓球

时间:2016-01-15 10:28:03

标签: javascript

我想在比赛中加快球速。 这是我的乒乓球代码:

Ball.prototype = {
  Draw : function () {   

    this.context.fillStyle = this.color;

    this.context.fillRect( this.posX, this.posY, this.diameter, this.diameter );

  },

    GetBallDirection : function () {
    if ( this.pitchX > 0 ) {
      return "right";
    } else if ( this.pitchX < 0 ) {
      return "left";
    }
    return "none";
  },

  Update : function () {
    this.posX += this.pitchX;

    if ( this.posX > this.courtWidth )
      return 1;

    if ( this.posX + this.diameter <= 0 )
      return 2

    this.posY += this.pitchY;
    if ( this.posY > this.courtHeight || this.posY <= 0 ) {
      this.pitchY = - this.pitchY;
    }

    return 0;
  },

     Center : function () {
    this.posX = this.courtWidth / 2 - this.diameter / 2;
    this.posY = this.courtHeight / 2 - this.diameter / 2;
  }
}

2 个答案:

答案 0 :(得分:3)

目前,您可以使用以下代码更新球的位置:

Update : function () {
    this.posX += this.pitchX;
    //(...)
    this.posY += this.pitchY;
    //(...)
  },

字面意思:“使用this.pitchX在x轴上移动球,使用this.pitchY在y轴上移动”

要改变球的速度,最好的办法是创建一个“速度”属性,然后使用它。像这样:

this.speed = 1; // Speed = normal (100%)

现在我们可以调整我们的Update - 函数:

Update : function () {
    this.posX += (this.pitchX * this.speed);
    //(...)
    this.posY += (this.pitchY * this.speed);
    //(...)
  },

现在,如果你想加速或减速,你只需将this.speed更改为其他内容。

this.speed = 0.5; //Ball will go half as fast
this.speed = 2; //Ball will go twice as fast.
this.speed += 0.01; //Ball will speed up with 1% each update.

答案 1 :(得分:0)

要加快球的速度,您可以在update功能中更改此项:

this.posY += (this.pitchY*2);
this.posX += (this.pitchX*2);

所以球的速度会快两倍。