Bouncing golf ball sinks into the ground
in
Programming Questions
•
2 years ago
I'm creating a sketch for class that will eventually let the user hit a golf ball in an attempt to make it into a hole. The ball will be affected by the friction caused by the ground, wind speed and direction, and intermittent obstacles. The code is still very primitive however, as about 90% of the time when the ball hits the ground it then vibrates erratically and slowly sinks into the ground. I assume this is being caused by the ball dropping slightly below the restricted area (385 pixels) and being reflected up and down instantaneously because it remains below said area.
I searched through the forums for other newbies trying to solve their bouncing ball issues, and the only one I could find contained a solution that resulted in the same issue. Any help is appreciated. Code to follow:
I searched through the forums for other newbies trying to solve their bouncing ball issues, and the only one I could find contained a solution that resulted in the same issue. Any help is appreciated. Code to follow:
- float ballX = 100.;
- float ballY = 385.;
- float gravity = .4;
- float ballSpeedX = 10.;
- float ballSpeedY = random(-15., -5.8);
- float windSpeed = random(-.5, .5);
- Cloud c1 = new Cloud(random(100, 1400), random(250), windSpeed);
- Cloud c2 = new Cloud(random(100, 1400), random(250), windSpeed);
- Cloud c3 = new Cloud(random(100, 1400), random(250), windSpeed);
- Cloud c4 = new Cloud(random(100, 1400), random(250), windSpeed);
- Cloud c5 = new Cloud(random(100, 1400), random(250), windSpeed);
- void setup() {
- size(1500, 400);
- smooth();
- noStroke();
- }
- void draw() {
- background(140, 200, 210);
- fill(100, 150, 50);
- rect(0, 390, width, height);
- fill(255, 0, 0, 200);
- triangle(1400, 340, 1400, 360, 1425, 350);
- strokeWeight(3);
- stroke(0);
- line(1400, 340, 1400, 390);
- noStroke();
- fill(0, 0, 0, 200);
- rect(1393, 390, 14, 10);
- fill(255, 255, 255, 255);
- c1.update();
- c2.update();
- c3.update();
- c4.update();
- c5.update();
- ellipse(ballX, ballY, 8, 8);
- ballX = ballX + ballSpeedX;
- ballY = ballY + ballSpeedY;
- ballSpeedY = ballSpeedY;
- if (ballX >= width) {
- ballSpeedX = ballSpeedX * -1.;
- }
- if (ballX <= 0) {
- ballSpeedX = ballSpeedX * -1.;
- }
-
- //FRICTION
- if (ballY >= 385) {
- ballSpeedY = ballSpeedY * -.5;
- ballSpeedX = ballSpeedX * .5;
- }
- //GRAVITY
- ballSpeedY += gravity;
- }
1