我正在使用像这样的精灵表(用于桨)和另一个用于球的精灵表制作乒乓球游戏:
我想要的是仅将红色图像检测为碰撞而不是蓝色图像:
我创建了一个 Spritesheet 类来帮助我处理动画:
import pygame
class Spritesheet(pygame.sprite.Sprite):
def __init__(self, filename, cols, rows, color_key = None):
super().__init__()
self.sheet = pygame.image.load(filename)
if color_key:
self.sheet = self.sheet.convert()
self.sheet.set_colorkey(color_key)
else:
self.sheet = self.sheet.convert_alpha()
w = self.sheet.get_width() / cols
h = self.sheet.get_height() / rows
self.index = 0
self.cells = list([pygame.Rect(i % cols * w, (i // cols) * h, w, h) for i in range(cols * rows)])
self.rect = self.cells[self.index]
self.image = self.image_at(self.rect)
def image_at(self, rectangle, colorkey=None):
rect = pygame.Rect(rectangle)
image = pygame.Surface(rect.size).convert_alpha()
image.blit(self.sheet, rect)
return image
def animate(self):
self.rect = self.cells[self.index % len(self.cells)]
self.index += 1
def animate_full(self, bouncing):
self.rect = self.cells[self.index % len(self.cells)]
if 0 <= self.index <= 2*len(self.cells):
self.animate()
return True
else:
self.index = 0
return False
def draw(self, surface, x, y):
surface.blit(self.sheet, (x, y), self.rect)
所以现在,在我的桨和球课上,我只写:
self.sprite = Spritesheet(filename, cols, rows, color)
self.rect = pygame.Rect(x, y, self.sprite.rect.w, self.sprite.rect.h)
self.mask = pygame.mask.from_surface(self.sprite.image)
最后,我尝试用这种代码检测像素完美碰撞:
# self.paddles is a pg.sprite.Group containing the 2 paddles on the game
if pg.sprite.spritecollide(self.ball, self.paddles, False, pg.sprite.collide_mask):
print("collision")
我不明白为什么我的代码不起作用,我的碰撞就像是一个简单的碰撞