Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!