Answer the question
In order to leave comments, you need to log in
How to write a horizontal bounce of a square (pygame)?
I don't understand how to make the square bounce off the walls horizontally in the update method.
I tried using loops but it didn't work either. It turns out to do only so that the rectangle reaches one of the walls, it does not go further.
import pygame
WIDTH = 360 # Ширина игрового окна
HEIGHT = 480 # Высота игрового окна
FPS = 60 # Частота кадров в секунду
# Цвета (R, G, B)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
def update(self):
if self.rect.right < WIDTH:
self.rect.x += 5
elif self.rect.left > WIDTH:
self.rect.x -= 5
# Создаём игру и окно
pygame.init()
pygame.mixer.init() # Звук
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('My game')
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# Цикл игры
running = True
while running:
# Держим цикл на правильной скорости
clock.tick(FPS)
# Ввод процесса (события)
for event in pygame.event.get():
# Проверяем закрытие окна
if event.type == pygame.QUIT:
running = False
# Обновление
all_sprites.update()
# Рендеринг
screen.fill(BLACK)
all_sprites.draw(screen)
# После отрисовки всего, переворачиваем экран
pygame.display.flip()
pygame.quit()
Answer the question
In order to leave comments, you need to log in
Because this check loops the square near the border: as soon as it starts going in the opposite direction, the first condition is triggered and it changes direction again.
The bounce is usually done by changing the sign of the increase in distance (velocity) on each of the boundaries.
def __init__(self):
....
self.speed = SPEED
def update(self):
self.rect.x += self.speed
if self.rect.left < 0 or self.rect.right > WIDTH:
self.speed = -self.speed
Add a SPEED variable with a value of 5 ( SPEED = 5 ) and in the __init__ method self.speed = SPEED
(if you know about Class in Python, you can easily do it and understand why, otherwise learn python, and then be interested in the Pygame library)
def update(self):
self.rect.x += self.speed
if self.rect.left < 0 or self.rect.right > WIDTH:
self.speed = -self.speed
self.rect.x += self.speed #speed = 5
if self.rect.left < 0 or self.rect.right > WIDTH:
self.rect.x += self.speed #speed = -5
until the left side of the object reaches the left side of the window =3
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question