pygame - 掩码碰撞不起作用,return 总是相同的碰撞点

pygame - mask collision not working, return always same collision point

我正在尝试创建像素完美的碰撞,但如果我尝试打印碰撞值,我总是会在点 (8, 0) 上发生碰撞。这是我的代码,谢谢。

collisionsroom1 = pygame.image.load("images/collisionsroom1.png")
characterhitbox = pygame.image.load("images/characterhitbox.png")

def collision():
  mouseposx, mouseposy = pygame.mouse.get_pos()
  ROOTwidth, ROOTheight = pygame.display.get_surface().get_size()

  #room 1 collision
  collisionsroom1 = pygame.transform.scale(collisionsroom1, (ROOTwidth/2.3, ROOTheight))
  ROOT.blit(collisionsroom1, [ROOTwidth/2-room1_width/2,0])
  collisionsroom1_mask = pygame.mask.from_surface(collisionsroom1)

  #character hitbox
  characterhitbox = pygame.transform.scale(characterhitbox, (ROOTheight/30, ROOTheight/30))
  characterhitbox_width = characterhitbox.get_width()
  characterhitbox_height = characterhitbox.get_height()
  ROOT.blit(characterhitbox, [mouseposx-characterhitbox_width/2, mouseposy- 
  characterhitbox_height/2])

  while True:
     mouseposx, mouseposy = pygame.mouse.get_pos()

     #get character updated mask position
     ROOT.blit(characterhitbox, [mouseposx-characterhitbox_width/2, mouseposy- 
     characterhitbox_height/2])
     characterhitbox_mask = pygame.mask.from_surface(characterhitbox)

     #room collisions
     offset = 0, 0

     collision = characterhitbox_mask.overlap(collisionsroom1_mask, offset)

     print (collision)
     if collision:
        print("yescollision")
     else:
        print("nocollision")

参见。由于 offset = 0, 0,您的代码无法运行。偏移量必须是图像左上角之间的距离:

offset = (character_x - room_x), (charcater_y - room_y)
collision = characterhitbox_mask.overlap(collisionsroom1_mask, offset)

在上面的例子中,(room_x, room_y)是房间的位置,(character_x, character_y)是角色的位置。