Skip to content

Commit

Permalink
Changes in update() function
Browse files Browse the repository at this point in the history
Expressions like "this.velX = -this.velX" have been replaced with "this.velX = -(Math.abs(this.velX))". The reason is to avoid some unexpected behaviour if the ball was initially drawn with coordinate x =  width - size and velX being already negative. Then, the condition "this.x + this.size >= width" would be satisfied, velX would become positive and the ball would move further to the right. After that, velX would be restored to its original (negative) value and the ball would bounce to the left, in the next step to the right, and so on. In effect, the ball would never abandon the right side of the canvas.
  • Loading branch information
Kamil-Orzechowski authored Sep 24, 2022
1 parent a9de148 commit d92413e
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions javascript/oojs/bouncing-balls/main-finished.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,19 @@ class Ball {

update() {
if ((this.x + this.size) >= width) {
this.velX = -(this.velX);
this.velX = -(Math.abs(this.velX));
}

if ((this.x - this.size) <= 0) {
this.velX = -(this.velX);
this.velX = Math.abs(this.velX);
}

if ((this.y + this.size) >= height) {
this.velY = -(this.velY);
this.velY = -(Math.abs(this.velY));
}

if ((this.y - this.size) <= 0) {
this.velY = -(this.velY);
this.velY = Math.abs(this.velY);
}

this.x += this.velX;
Expand Down

0 comments on commit d92413e

Please sign in to comment.