首页 > 后端开发 > Python教程 > 如何在 Pygame 中检测矩形之间的碰撞?

如何在 Pygame 中检测矩形之间的碰撞?

Barbara Streisand
发布: 2024-12-24 13:55:16
原创
434 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板