M
M
MeHox2022-02-21 22:35:04
pygame
MeHox, 2022-02-21 22:35:04

How to implement collision in pygame?

I need to collide the green square so that the player's center cannot go through its walls.
You can't just do it with ifs, because the object will then be moved or even deleted.

import sys, pygame

pygame.init()

FPS = 60
SCREEN = (640, 480)
screen = pygame.display.set_mode(SCREEN)
rect = pygame.Rect(100, 100, 200, 200) # объект для хранения прямоугольных координат
player = pygame.Rect(20, 20, 40, 40)

x_player = 50
y_player = 50
speed = 1

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: # выход
            pygame.quit()
            sys.exit()
    # передвижение персонажа ↓
    keys = pygame.key.get_pressed()
    if keys[pygame.K_d] and x_player < SCREEN[0]:
        x_player += speed
    if keys[pygame.K_a] and x_player > 0:
        x_player -= speed
    if keys[pygame.K_s] and y_player < SCREEN[1]:
        y_player += speed
    if keys[pygame.K_w] and y_player > 0:
        y_player -= speed
    if keys[pygame.K_LSHIFT] and speed < 2:
        speed += 1
    if not keys[pygame.K_LSHIFT] and speed > 1:
        speed -= 1
    # передвижение персонажа ↑

    # правильная коллизия ↓
    if x_player <= -1:
        x_player = 0
    if y_player <= -1:
        y_player = 0
    if x_player >= SCREEN[0]:
        x_player = SCREEN[0]
    if y_player >= SCREEN[1]:
        y_player = SCREEN[1]


    # коллизия на объекты просто так не работает, нужно сделать отдельные 8 префабов для коллизии
    if rect.collidepoint(x_player, y_player):
        y_player -= speed
        print("collision")

    # правильная коллизия ↑


    # print(x_player, y_player)

    screen.fill((0,0,0))
    pygame.draw.circle(screen, "YELLOW", (x_player, y_player), 10)
    pygame.draw.rect(screen, "GREEN", (100, 100, 200, 200))
    pygame.display.update()
    pygame.time.Clock().tick(FPS)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2022-02-22
@phaggi

You need to use the search on the site with a request

pygame collision
and work through the results. This is a common question and there are many answers. If what has already been answered is not enough for you, I doubt the success in the case of your question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question