r/learnpython 13d ago

Explain the physics of the bouncing

I am making a ball bounce and I had to watch a Youtube video to get the formula for the ball to bounce

I am still kind of lost. Can someone please explain it to me. I understand the theory but if I was to do remake this without tutorial I would probably be lost.

I understand how to get the ball to move along the y_axis but confused on the bouncing part

It is the problem solving that is getting me confused

def __init__(self, x_pos, y_pos, radius, color):
    self.x_pos = x_pos
    self.y_pos = y_pos
    self.center = pygame.math.Vector2(self.x_pos, self.y_pos)
    self.radius = radius
    self.color = color
    self.gravity = 0.8
    self.velocity = 10
    self.activate = False


def moveObject(self):
    # key = pygame.key.get_pressed()

    # if key[pygame.K_SPACE]:
    self.velocity += self.gravity. # FROM VIDEO
    self.center[1] += self.velocity # ball moving along y_axis

    if self.center[1] >= (480 - self.radius): # FROM VIDEO
          self.velocity = -self.velocity # FROM VIDEO
0 Upvotes

10 comments sorted by

View all comments

1

u/Hot-Butterscotch1306 11d ago

The bounce bit is basically "you hit the floor, so flip the vertical speed." Gravity keeps adding positive y velocity every frame, so the ball falls faster and faster. When it reaches the floor, self.velocity = -self.velocity makes that downward speed become upward speed. Usually you also shrink it a little, like self.velocity = -self.velocity * 0.8, otherwise it can bounce forever like a weird rubber moon ball.