Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda