We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am trying to program a Bouncing 2d ball in p5.js and im having some trouble. Whenever the Ball is done bouncing It goes crazy and i cant get it to end. and can you maybe tell me a way better way to do this im new in the whole Nature Of Code thing.
Heres My Code
`
var x = 50; var y = 50; var xspeed = 2; var yspeed = 1; var gravity = .63;
var r = 25; function setup() { createCanvas(800, 600); background(255, 255, 0); ellipse(x, y, 50, 50); }
function draw() {
y = y + yspeed;
yspeed = yspeed + gravity;
if((y + r) >= 600){
yspeed = (yspeed - 3) * -1;
}
background(255, 255, 0);
ellipse(x, y, 50, 50);
if(y > 610){
return;
console.log("terminate");
}
}
`
^ Its not showng the first part as code is that a bug or something
Answers
After the line
if((y + r) >= 600){
Add this line of code:y = 600 - r;
Ok that did help but can you explain why to help me later in this project
To format your code, press the gear icon to edit your post. Select your code and press ctrl + o (or the C button, but only after selecting your code) to indent, and leave a line above and below the code.
This is a rather standard bug that many beginners end up creating - sometimes the speed is so great that when it "hits" the ground, it ends up so much underneath it that in the next frame also it remains under the ground. Then the direction of the ball again reverses and this process repeats endlessly.
The fix, then, is to set the ball to a position that isn't below the ground once it's position is below the ground. Hence the addition of the above line of code. This also ensures that, on the next frame, it won't be below the ground any longer, and so will bounce up again.
Thx Guys so much I'm trying to learn this whole nature of code thing