pygame - 掩模碰撞不起作用,始终返回相同的碰撞点

问题描述 投票:0回答:1

我正在尝试创建像素完美的碰撞,但如果我尝试打印碰撞值,我总是会发现碰撞发生在点 (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")
python pygame collision-detection offset mask
1个回答
1
投票

参见 PyGame 与遮罩的碰撞。由于

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
) 是角色的位置。

© www.soinside.com 2019 - 2024. All rights reserved.