繁体   English   中英

如何在js中的Pong中加速球

[英]How to accelerate the ball in pong in js

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

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;
  }
}

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

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.

为了加快球的速度,您可以在update功能中对此进行更改:

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

因此,球将快两倍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM