P
P
pyblpovishaisa2020-12-28 21:53:47
Python
pyblpovishaisa, 2020-12-28 21:53:47

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

2 answer(s)
O
o5a, 2020-12-29
@pyblpovishaisa

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

S
SKAIT de Cato, 2020-12-30
@SKAIT

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

(don't forget that whatever you put in the update() method will happen every frame.)
In this block of code, every frame, or rather every 0.02 sec, the following happens:
self.rect.x += self.speed #speed = 5
your rectangle has moved to the right by 5, because the SPEED is 5 next step
if self.rect.left < 0 or self.rect.right > WIDTH:
checks whether the left edge of the object has reached the left side of the window or the right side of the object has reached the right side of the window, if at least one of these two conditions is true, then proceeds to the execution of the if block, if none of them is true, then everything starts over ( moves 5 to the right and checks the condition).
As soon as the object has reached the right side, then speed changes its value to -5 and now the rectangle will go to the left self.rect.x += self.speed #speed = -5until the left side of the object reaches the left side of the window =3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question