I am brand new to JavaScript and p5.js. While I realize this may not be the most efficient code for a bouncing ball, I wanted to challenge myself by writing my own bouncing ball mechanic as part of my self-learning journey.
function draw() {
background (col); // setting background color
col = map(cir.x, 0, 600, 0, 255) // mapping color values
fill (350, 200, 200);
ellipse (cir.x, cir.y, cir.diameter, cir.diameter);
// Bouncing ball mechanism
var speed = 3;
var hitRightWall = false;
var hitLeftWall = false;
if (cir.x >= 300) {
hitRightWall = true;
hitLeftWall = false;
}
else if (cir.x <= -50) {
hitLeftWall = true;
hitRightWall = false;
}
if (hitRightWall) {
speed = -3;
}
else {
speed = 3;
}
cir.x = cir.x + speed;
}
Despite activating the if (cir.x >= 300)
condition, the if (hitRightWall==True)
condition is never triggered. As a result, the ball continuously moves right and eventually off the screen.