PyGame 碰撞仅在矩形的一侧起作用

PyGame Collisions does only work on one side of the rectangle

我只是在尝试一些碰撞并找到了检查矩形一侧与另一侧的方法。

我有以下问题:

如果我将我的游戏角色(粉红色框)从左侧移动到物体上,我的游戏角色就会穿过它:

如果我来自另一边,一切正常,我的游戏角色停止。

我的意思是说我需要两边都使用相同的代码,但必须将两边从 if not player_rect.left == other_rect.right: 更改为 if not player_rect.right == other_rect.left:。但这对一侧不起作用。

import pygame
import sys

pygame.init()

clock = pygame.time.Clock()
window = pygame.display.set_mode([1200, 800])
pygame.display.set_caption("Collision Test")

x = 300
y = 300
width = 48
height = 96
velocity = 5

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        is_pressed = pygame.key.get_pressed()
        player_rect = pygame.Rect(x, y, width, height)
        other_rect = pygame.Rect(400, 300, 50, 50)

        if is_pressed[pygame.K_d]:
            if not player_rect.right == other_rect.left:
                x += velocity
        if is_pressed[pygame.K_a]:
            if not player_rect.left == other_rect.right:
                x -= velocity

    window.fill((100, 150, 50))
    pygame.draw.rect(window, (255, 50, 100), player_rect)
    pygame.draw.rect(window, (255, 100, 50), other_rect)
    pygame.display.update()
    clock.tick(60)

使用collideRect().

移动对象并测试矩形是否发生碰撞。当检测到碰撞时,根据移动方向改变物体的位置:

is_pressed = pygame.key.get_pressed()
move_right = is_pressed[pygame.K_d]
move_left = is_pressed[pygame.K_a]

if move_right:
    x += velocity
if move_left:
    x -= velocity

player_rect = pygame.Rect(x, y, width, height)
other_rect = pygame.Rect(400, 300, 50, 50)

if player_rect.colliderect(other_rect):
    if move_right:
        player_rect.right = other_rect.left
        x = player_rect.left
    if move_left:
        player_rect.left = other_rect.right
        x = player_rect.left

为了平稳移动,您必须在应用程序循环而不是事件循环中评估 pygame.key.get_pressed()
另见

import pygame
import sys

pygame.init()

clock = pygame.time.Clock()
window = pygame.display.set_mode([1200, 800])
pygame.display.set_caption("Collision Test")

x = 300
y = 300
width = 48
height = 96
velocity = 5

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    is_pressed = pygame.key.get_pressed()
    move_right = is_pressed[pygame.K_d]
    move_left = is_pressed[pygame.K_a]

    if move_right:
        x += velocity
    if move_left:
        x -= velocity

    player_rect = pygame.Rect(x, y, width, height)
    other_rect = pygame.Rect(400, 300, 50, 50)

    if player_rect.colliderect(other_rect):
        if move_right:
            player_rect.right = other_rect.left
            x = player_rect.left
        if move_left:
            player_rect.left = other_rect.right
            x = player_rect.left

    window.fill((100, 150, 50))
    pygame.draw.rect(window, (255, 50, 100), player_rect)
    pygame.draw.rect(window, (255, 100, 50), other_rect)
    pygame.display.update()
    clock.tick(60)