如何为矩形的所有4个边创建碰撞?示例:如果玩家进入左侧,则无法再向右移动。如果它落在矩形的顶部,它会停止下降等。
答案 0 :(得分:1)
我会看看PyGame Rects。具体来说,请查看pygame.Rect.colliderect。
Bellow我已经将代码粘贴到一个非常简单的骨头游戏中,我相信这些游戏概述了你正在寻找的东西。
import pygame
pygame.init()
screen = pygame.display.set_mode((700, 400))
clock = pygame.time.Clock()
BLACK, WHITE, GREY = (0, 0, 0), (255, 255, 255), (100, 100, 100)
block_x, block_y = 25, 175
speed_x, speed_y = 0, 0
run = 1
while run:
for e in pygame.event.get():
if e.type == pygame.QUIT:
run = 0
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_LEFT:
speed_x = -5
speed_y = 0
if e.key == pygame.K_RIGHT:
speed_x = 5
speed_y = 0
if e.key == pygame.K_UP:
speed_x = 0
speed_y = -5
if e.key == pygame.K_DOWN:
speed_x = 0
speed_y = 5
screen.fill(BLACK)
block_x += speed_x
block_y += speed_y
blockOne_rect = pygame.Rect(block_x, block_y, 50, 50)
blockTwo_rect = pygame.Rect(600, 175, 50, 50)
pygame.draw.rect(screen, WHITE, blockOne_rect)
pygame.draw.rect(screen, GREY, blockTwo_rect)
if blockOne_rect.colliderect(blockTwo_rect):
speed_x = 0
speed_y = 0
clock.tick(60)
pygame.display.update()
pygame.quit()
quit()