[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] Why does my ball vibrate?



Hi,

I am beginning to learn Pygame and I have written a short program to simulate a bouncing ball. The motion of the ball is pretty realistic until it has almost come to rest. The ball continues to vibrate long after you would have expected it to come to a complete rest (or be moving less than 1 pile each time as it will never stop moving 100%). Also, the ball can start to bounce higher again if I click somewhere else on the desktop. I can't work out why this happens so can anyone shed some light on it and suggest how I can prevent it.Here's my code:

#! /usr/bin/python

import sys, pygame
pygame.init()

xpos = 92
ypos = 0
gravity = 9.8
velocity = 0
# How much of the velocity of the ball is retained on a bounce
bounce = 0.8

screen = pygame.display.set_mode((200, 400), 0, 32)
# The ball is a 16px sprite
ball = pygame.image.load('ball.png')
clock = pygame.time.Clock()

# The main loop
while True:

    # Test for exit
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    # The physics
    # Reverse velocity taking into account bounciness if we hit the ground
    if ypos == 384 and velocity > 0:
        velocity = -velocity * bounce
    time_passed = clock.tick(60) / 1000.0
    newvelocity = velocity + (gravity * time_passed)
# Use the average velocity over the period of the frame to change position
    ypos = ypos + (((velocity + newvelocity) / 2) * time_passed * 160)
    # Prevent the ball from sinking into the ground
    if ypos >= 384:
        ypos = 384
    velocity = newvelocity

    # Update the screen
    screen.fill((0, 0, 0))
    screen.blit(ball, (xpos, ypos))
    pygame.display.update()

Thanks for looking.

Matt