首頁 >後端開發 >Python教學 >如何在 Pygame 中偵測矩形之間的碰撞?

如何在 Pygame 中偵測矩形之間的碰撞?

Barbara Streisand
Barbara Streisand原創
2024-12-24 13:55:16443瀏覽

How to Detect Collisions Between Rectangles in Pygame?

如何在Pygame 中檢測兩個矩形物體或圖像之間的碰撞

問題:

您正在開發一款遊戲,碗必須接住掉落的物品。您有物品和碗的圖像,但不確定如何檢測它們之間的碰撞。

import math
import pygame
import random

# Game initialization
pygame.init()
# Screen dimensions
display_width = 800
display_height = 600

# Initialize the screen
game_display = pygame.display.set_mode((display_width, display_height))
# Set the clock
clock = pygame.time.Clock()
# Game title
pygame.display.set_caption("Catch the Ball")

# Colors and images
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 255, 0)

player_img = pygame.image.load("Images/soup.png")
thing_imgs = [
    pygame.image.load('Images/muffin.png'),
    pygame.image.load('Images/dessert.png'),
    pygame.image.load('Images/cheese.png'),
    pygame.image.load('Images/fruit.png'),
]


def player(x, y):
    game_display.blit(player_img, (x, y))


def things(x, y, img):
    game_display.blit(img, (x, y))


def game_loop():
    running = True

    x = display_width * 0.45
    y = display_height * 0.8
    x_change = 0

    player_width = 64
    player_height = 64

    things_cor = [[random.randint(0, display_width), 32]]
    things_added = [random.choice(thing_imgs)]
    thing_height = 32
    thing_width = 32
    y_change = 5

    caught = 0

    while running:
        for event in pygame.event.get():
            # Quit the game
            if event.type == pygame.QUIT:
                running = False

            # Player movement
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -5

                if event.key == pygame.K_RIGHT:
                    x_change = 5

            # Stop player movement
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0

        # Clear the screen
        game_display.fill(white)

        player(x, y)
        # Update the player's position
        x += x_change

        for i in range(len(things_cor)):
            thing_x, thing_y = things_cor[i]
            things(thing_x, thing_y, things_added[i])

        for i in range(len(things_cor)):
            things_cor[i][1] += y_change
            # Reset the item to the top of the screen if it goes off the bottom
            if things_cor[i][1] > display_height:
                things_cor[i][1] = random.randint(-2000, -1000)
                things_cor[i][0] = random.randint(0, display_width)
                things_added[i] = random.choice(thing_imgs)

                # Add a new item if the list is less than 6
                if len(things_added) < 6:
                    things_cor.append(
                        [random.randint(0, display_width), -10]
                    )

        # Limit player movement
        if x < 0:
            x = 0
        elif x > display_width - player_width:
            x = display_width - player_width

        # Delay the game start by 100 seconds
        passed_time = pygame.time.get_ticks()  # Time in milliseconds
        start_time = 100 * 1000  # Start time in milliseconds

        # Update the scene and display
        if passed_time >= start_time:
            game_display.fill(white)
            player(x, y)
            for i in range(len(things_cor)):
                thing_x, thing_y = things_cor[i]
                things(thing_x, thing_y, things_added[i])
            pygame.display.update()

        # Set the frame rate
        clock.tick(60)


game_loop()

解決方案:

偵測兩個矩形物件之間的碰撞或 Pygame 中的影像,使用 pygame.Rect 物件和 colliderect()方法:

# Create rectangles for the player and the items
player_rect = player_img.get_rect(topleft = (x, y))
for i in range(len(things_cor)):
    thing_rect = things_added[i].get_rect(topleft = things_cor[i])

# Check for collisions
if player_rect.colliderect(thing_rect):
    print("hit")

By將此程式碼放入遊戲循環中,您可以持續檢查玩家和物品之間的碰撞。

以上是如何在 Pygame 中偵測矩形之間的碰撞?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn