所以,我试图检测我的病毒和矩形之间的冲突,我为每个人设置了类,我有碰撞的代码,但代码最终没有工作,我不知道是什么错误。我已将图像转换为矩形并使用colliderect来检测病毒与基座之间的碰撞,但没有任何反应。任何帮助将被理解为什么这是!
import pygame, random, time
pygame.init()
#Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
#Screen Stuff
size = (1080, 640)
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Random Platformer')
icon = pygame.image.load('Icon.jpg')
pygame.display.set_icon(icon)
pygame.display.update()
#Misc Stuff
clock = pygame.time.Clock()
running = True
#Objects
class Player:
def __init__(self, x, y, image):
self.x = x
self.y = y
self.player = pygame.image.load(image)
self.rect = self.player.get_rect()
def load(self):
screen.blit(self.player, (self.x, self.y))
def move_right(self):
self.x += 7.5
def move_left(self):
self.x -= 7.5
def move_up(self):
self.y -= 7.5
def move_down(self):
self.y += 7.5
class Block:
def __init__(self, x, y, width, length, edge_thickness):
self.x = x
self.y = y
self.width = width
self.length = length
self.edge_thickness = edge_thickness
def load(self):
self.rect = pygame.draw.rect(screen, BLACK, [self.x, self.y,
self.width, self.length], self.edge_thickness)
#Players
virus = Player(100, 539, 'Virus.jpg')
#Blocks
level_base = Block(0, 561, 1080, 80, 0)
#Game Loop
while running:
#Level Generation
screen.fill(WHITE)
level_base.load()
virus.load()
if level_base.rect.colliderect(virus.rect):
print ('Hi')
#Controls
key_press = pygame.key.get_pressed()
if key_press[pygame.K_d]:
virus.move_right()
if key_press[pygame.K_a]:
virus.move_left()
if key_press[pygame.K_w]:
virus.move_up()
if key_press[pygame.K_s]:
virus.move_down()
#Game Code
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
break
pygame.display.flip()
clock.tick(60)
答案 0 :(得分:0)
如果碰撞检测不起作用,则每帧打印所涉及对象的rect
是有帮助的。您会看到virus
的矩形位于屏幕的左侧坐标(0,0)处,并且在病毒移动时不会移动。
在__init__
方法中,您必须设置self.rect
的坐标,例如将x和y作为topleft
或center
参数传递给get_rect:< / p>
self.rect = self.player.get_rect(topleft=(x, y))
你也可以这样做:
self.rect.x = x
self.rect.y = y
当玩家移动时,你总是要更新矩形。您也可以使用update
方法执行此操作。
class Player:
def __init__(self, x, y, image):
self.x = x
self.y = y
self.player = pygame.image.load(image)
self.rect = self.player.get_rect(topleft=(x, y))
def load(self):
screen.blit(self.player, self.rect)
def move_right(self):
self.x += 7.5
self.rect.x = self.x
def move_left(self):
self.x -= 7.5
self.rect.x = self.x
def move_up(self):
self.y -= 7.5
self.rect.y = self.y
def move_down(self):
self.y += 7.5
self.rect.y = self.y