我正在编写一个小游戏等等,一切都在工作,但有一个问题。
我不知道如何编写播放器和墙壁之间的碰撞检测代码。必须有一种方法能够检查玩家在执行步骤之前是否会撞到墙壁。
下面是我的代码:import pygame, sys, random
gameover = False
player_in_radius = False
key_picked = False
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (50, 50, 255)
GREY = (238,223,204)
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, image):
super().__init__()
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
self.walls = None
class Wall(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
super().__init__()
# Make a blue wall, of the size specified in the parameters
self.image = pygame.Surface([width, height])
self.image.fill(BLACK)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
pygame.init()
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 900
clock = pygame.time.Clock()
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
pygame.display.set_caption("EscapefromHoney / ETAGE 0")
all_sprite_list = pygame.sprite.Group()
wall_list = pygame.sprite.Group()
wall = Wall(0, 0, 10, 900)
wall_list.add(wall)
all_sprite_list.add(wall)
wall = Wall(1190, 0, 10, 900)
wall_list.add(wall)
all_sprite_list.add(wall)
wall = Wall(0, 890, 1200, 10)
wall_list.add(wall)
all_sprite_list.add(wall)
wall = Wall(10, 0, 1200, 10)
wall_list.add(wall)
all_sprite_list.add(wall)
wall = Wall(10, 200, 120, 10)
wall_list.add(wall)
all_sprite_list.add(wall)
player = Player(50, 50, "pictureskian60x60.png")
player.walls = wall_list
all_sprite_list.add(player)
while 1:
if key_picked == False:
key = pygame.image.load("pictureskey.png")
keyrect = key.get_rect()
keyrect.top = 600
keyrect.left = 480
screen.blit(key, keyrect)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_DOWN:
player.rect.y = player.rect.y + 60
if event.key == pygame.K_UP:
player.rect.y = player.rect.y - 60
if event.key == pygame.K_RIGHT:
player.rect.x = player.rect.x + 60
if event.key == pygame.K_LEFT:
player.rect.x = player.rect.x - 60
all_sprite_list.update()
screen.fill(GREY)
all_sprite_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
我试图使用这个代码
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
# If we are moving right, set our right side to the left side of
# the item we hit
if self.change_x > 0:
self.rect.right = block.rect.left
else:
# Otherwise if we are moving left, do the opposite.
self.rect.left = block.rect.right
但是没有机会。还是不行。另一点,我不想把整个变化量和速度放在一起。我只需要像我在代码中那样的步骤。
你的播放器和你的墙都是rects:
因此你可以简单地使用。colliderect()方法:
player.rect.colliderect(wall.rect)
或
wall.rect.colliderect(player.rect)
如果两个矩形重叠,都返回true。
如果你想要更多的控制,只需在你的类中添加一个hitbox属性,它将是一个你想要的碰撞检测区域大小的矩形,然后使用hitbox rect
快乐编程