Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register an exact X/Y boundary crossing when object is moving more than 1 pixel per update?

Tags:

python

pygame

I'm trying to learn Python/Pygame and I made a simple Pong game. However I cannot get the square to bounce off the sides at the perfect pixel as the drawing of the square is updating let's say 3 pixels every frame.

I have a code to decide when the square is hitting the edges and bounce in a reverse direction like this:

if y_ball < 100:
        y_ball_change = y_ball_change * -1     
if y_ball > 675:
        y_ball_change = y_ball_change * -1
if x_ball > 775:
        x_ball_change = x_ball_change * -1

if x_ball <= x_rect + 25 and y_ball >= y_rect -25 and not y_ball > y_rect + 150:
        x_ball_change = x_ball_change * -1 +2

It's keeping the square inside the boundaries of the screen however it's not pixel perfect since

x_ball_change
y_ball_change

is often more/less than 1 since they are randomized between -5 and 5 (except 0) to make starting direction of the ball random every new game.

Thanks for any help!

like image 755
Zoler1337 Avatar asked Oct 27 '22 09:10

Zoler1337


1 Answers

You also need to correct the position of the ball when changing the direction of the ball. The ball bounces on the boundaries and moves the excessive distance in the opposite direction like a billiard ball:

e.g.:

if y_ball < 100:
    y_ball = 100 + (100 - y_ball)
    y_ball_change = y_ball_change * -1     

if y_ball > 675:
    y_ball = 675 - (y_ball - 675)
    y_ball_change = y_ball_change * -1

if x_ball > 775:
    x_ball = 775 - (x_ball - 775)
    x_ball_change = x_ball_change * -1

if x_ball <= x_rect + 25 and y_rect -25 <= y_ball <= y_rect + 150:
    x_ball = x_rect + 25 + (x_rect + 25 - x_ball)    
    x_ball_change = x_ball_change * -1 +2
like image 148
Rabbid76 Avatar answered Nov 16 '22 22:11

Rabbid76