Pygame与面具的碰撞不起作用
问题内容:
我做了一个推杆游戏,现在我想添加一个倾斜的墙类型。因此,我需要为碰撞使用蒙版(直到现在我才使用rects)。我花了数小时学习有关掩码的知识,并试图弄清为什么我的代码无法正常工作。没有错误,只是没有检测到冲突。
我已将代码简化为小得多的代码,以方便我高效地对其进行测试。从我所看到的一切来看,这似乎应该可行,但事实并非如此。这里是:
import pygame
# Pygame init stuff
pygame.init()
wind_width = 1200
wind_height = 700
gameDisplay = pygame.display.set_mode((wind_width, wind_height))
pygame.display.set_caption("Mini Golf!")
pygame.display.update()
gameExit = False
clock = pygame.time.Clock()
# Class setups
class Ball:
def __init__(self, x, y):
self.x = x
self.y = y
self.image = pygame.image.load("sball.png")
self.rect = self.image.get_rect()
self.mask = pygame.mask.from_surface(self.image)
def render(self):
self.rect.topleft = (self.x, self.y)
gameDisplay.blit(self.image, self.rect)
class Slant:
def __init__(self, x, y):
self.x = x
self.y = y
self.image = pygame.image.load("posslant.png")
self.rect = self.image.get_rect()
self.mask = pygame.mask.from_surface(self.image)
def render(self):
self.rect.topleft = (self.x, self.y)
gameDisplay.blit(self.image, self.rect)
# Creating objects
ball = Ball(250, 250)
slant = Slant(270, 250)
# Game loop
gameExit = False
while not(gameExit):
# Moves ball
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
ball.y -= 1
elif event.key == pygame.K_DOWN:
ball.y += 1
elif event.key == pygame.K_LEFT:
ball.x -= 1
elif event.key == pygame.K_RIGHT:
ball.x += 1
# Collision detection
offset_x, offset_y = (slant.rect.x - ball.rect.x), (slant.rect.y - ball.rect.y)
if slant.mask.overlap(ball.mask, (offset_x, offset_y)):
print("hit")
# Draws everything
gameDisplay.fill((0, 0, 0))
ball.render()
slant.render()
pygame.display.update()
clock.tick(100)
问题答案:
该方法的偏移参数overlap()
是的相对位置
othermask
相对于pygame.mask.Mask
对象。
因此,偏移量是通过减去以下坐标的坐标来计算slant
的ball
:
offset_x, offset_y = (slant.rect.x - ball.rect.x), (slant.rect.y - ball.rect.y)
offset = (ball.rect.x - slant.rect.x), (ball.rect.y - slant.rect.y)
if slant.mask.overlap(ball.mask, offset):
print("hit")
当您创建的掩模图像,那么我建议,以确保图像通过调用每像素阿尔法格式有.convert_alpha()
:
class Ball:
def __init__(self, x, y):
self.x = x
self.y = y
self.image = pygame.image.load("sball.png")
self.rect = self.image.get_rect()
self.mask = pygame.mask.from_surface(self.image.convert_alpha()) # <---
class Slant:
def __init__(self, x, y):
self.x = x
self.y = y
self.image = pygame.image.load("posslant.png")
self.rect = self.image.get_rect()
self.mask = pygame.mask.from_surface(self.image.image.convert_alpha()) # <---
最小示例: [![](https://i.stack.imgur.com/5jD0C.png) repl.it/@Rabbid76/PyGame- SurfaceMaskIntersect](https://repl.it/@Rabbid76/PyGame- SurfaceMaskIntersect#main.py)
另请参阅:面膜