如何在矩形的所有边上创建碰撞?

  • 本文关键字:创建 碰撞 python pygame
  • 更新时间 :
  • 英文 :


如何为矩形的所有 4 条边创建碰撞?示例:如果玩家碰到左侧,则无法再向右移动。如果它落在矩形的顶部,它就会停止下降,依此类推。

我会看看PyGame Rects。具体来说,看看pygame。直截了当。

贝娄 我已经将代码粘贴到一个非常简单的游戏中,我相信它概述了您正在寻找的内容。

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()

最新更新