Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda