【发布时间】:2020-10-20 10:43:31
【问题描述】:
我只是在尝试一些碰撞,并找到了检查矩形一侧与另一侧的方法。
我有以下问题:
如果我将我的游戏角色(粉红色框)从左侧移到对象上,我的游戏角色就会穿过它:
如果我来自另一边,一切正常,我的游戏角色停止。
我的意思是说我需要为双方提供相同的代码,但必须将双方从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)
【问题讨论】:
标签: python pygame collision-detection