Skip to content
Advertisement

How to put random numbers in Pygame

JavaScript

I expected the ball to move and every time it hits the corner change velocity.

Advertisement

Answer

To make the ball move, you’ve to use a variable for position wich can store floating point coordinates. The position is changed every frame depending on the speed. Finally the ball rectangle has to be updated with the position:

JavaScript

Note, the coordinates of pygame.Rect are integral values. If a positive floating point value which is less that 1 is added to an integral value, then the value doesn’t change at all, because the result is truncated to to the integral part again.

JavaScript

Ensure that the random velocity is always greater than 0.0. Generate a random velocity and change the speed dependent on the new direction:

e.g.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement