我试着做一个Zelda的克隆,现在我想知道如何计算碰撞,有人能告诉我怎么做吗?我已经尝试过colliderct,它根本不能工作,下面是我的代码:
import pygame
pygame.init()
display = pygame.display.set_mode((800,600))
white=(255,255,255)
black=(0,0,0)
x=50
y=50
width = 40
height = 60
vel = 5
playerimg= pygame.image.load('link1.jpg').convert()
def player(x,y):
display.blit(playerimg,(x,y))
while True:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
x -= vel
if keys[pygame.K_d]:
x += vel
if keys[pygame.K_w]:
y -= vel
if keys[pygame.K_s]:
y += vel
display.fill(white)
player(x,y)
pygame.draw.rect(display, (255,0,0), hitbox,2)
pygame.display.update()
pygame.quit()发布于 2020-07-19 15:19:40
你可以使用“hitboxes”来做这件事,现在你必须知道你的图像的尺寸,你可以这样做。
hitbox=(x,y, 102,131)
hitbox1=pygame.draw.rect(display, (255,0,0), hitbox,2)
if the_thing_it_hits.colliderect(hitbox) == True:
print('ouch')把这段代码放到while True:循环中,它应该是好的
发布于 2020-07-19 15:36:54
可以使用pygame.Rect和colliderect()执行碰撞测试。例如,您可以定义一个障碍物,然后通过get_rect()从playerimg获取矩形。测试两个矩形是否发生碰撞:
while True:
# [...]
hitbox = pygame.Rect(100, 100, 100, 100)
player_rect = playerimg.get_rect(topleft = (x, y))
if player_rect.colliderect(hitbox):
print("hit")
display.fill(white)
player(x,y)
pygame.draw.rect(display, (255,0,0), hitbox,2)
pygame.display.update() 无论如何,我推荐使用pygame.sprite.Sprite、pygame.sprite.Group和pygame.sprite.spritecollide()。
此外,您的QUIT事件的实现不会退出游戏
while True:对于pygame.event.get()中的事件: if event.type == pygame.QUIT: break
因为break语句只会中断事件循环,而不会中断应用程序循环。
请改用变量:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = Falsehttps://stackoverflow.com/questions/62977323
复制相似问题