Search code examples
pythongame-physics

how to make the ball stop bouncing?


I make a game that need the ball bounce. but the bounce is don't stop and always like that. The Code:

import pygame as pg
pg.init()

class Ball:
    def __init__(self):
        self.y = 250
        self.x = 250
        self.vel_y = 0
        self.jumpspdy = 0
    

    def move(self):
        self.vel_y += 1
        if self.vel_y > 20:
            self.vel_y = 20
        if self.y > 450:
            self.vel_y = -self.vel_y
        self.y += self.vel_y

    def draw(self):
        pg.draw.circle(screen, (255, 0 , 0), (self.x, self.y), 25)


screen = pg.display.set_mode((500, 500))
ball = Ball()
mousex, mousey = pg.mouse.get_pos()
clock = pg.time.Clock()
fps = 50

run = True
while run:
    for i in pg.event.get():
        if i.type == pg.QUIT:
            run = False
    screen.fill((0, 0, 0))
    ball.move()
    ball.draw()
    pg.display.update()
    clock.tick(fps)
pg.quit()

Can anyone help? :(

I try to search youtube but it's not helping. i want to make it stop bounce after few seconds.


Solution

  • self.vel_y = - self.vel_y
    

    This preserves momentum forever, causing the ball to bounce as high the second time as it did the first, and so on. To "lose" some momentum to the ground, multiply by a damping factor.

    self.vel_y = - self.vel_y * 0.95
    

    Any number from 0 to 1 (excluding bounds) will work. Numbers closer to 1 will result in a slower decay, while those closer to 0 will see the balls bounces decrease in height more quickly.

    If you want the ball to actually stop bouncing, rather than merely decaying into trivial bounces, then you can put an additional check after that for small velocity. Something like

    if abs(self.vel_y) < 0.1:
        self.vel_y = 0
    

    Again, your exact limits may vary, so try some different numbers till you get something you're happy with.