Frida Esala
Frida Esala

Reputation: 9

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

Upvotes: 0

Views: 432

Answers (2)

Jordumus
Jordumus

Reputation: 2783

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"

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 : 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 = 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.

Upvotes: 3

Zagonine
Zagonine

Reputation: 2313

To accelerate the speed of the ball you can change this in your update function :

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

So the ball will be twice as fast.

Upvotes: 0

Related Questions