简体   繁体   English

如何在js中的Pong中加速球

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

I would like to accelerate the ball speed in my game. 我想在比赛中加快球速。 Here is the code of my pong: 这是我的乒乓球的代码:

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

At the moment, you update your ball position with this code: 此刻,您可以使用以下代码更新球的位置:

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

Literally: "move the ball on the x-axis with this.pitchX, and on the y-axis with this.pitchY" 从字面上看:“使用this.pitchX在x轴上移动球,使用this.pitchY在y轴上移动球”

To change the speed of the ball, the best thing to do is create a "speed"-property, and use it. 要更改球的速度,最好的办法是创建一个“速度”属性,然后使用它。 Like this: 像这样:

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

Now we can adapt our Update -function: 现在,我们可以调整Update功能:

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

Now, if you want to speed up, or slow down the ball, you just change this.speed to something else. 现在,如果您想加快或降低球速,只需将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.

To accelerate the speed of the ball you can change this in your update function : 为了加快球的速度,您可以在update功能中对此进行更改:

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

So the ball will be twice as fast. 因此,球将快两倍。

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

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