pygame-KidsCanCode系列jumpy-part17-mask-collide碰撞检测

时间:2023-03-10 07:19:30
pygame-KidsCanCode系列jumpy-part17-mask-collide碰撞检测

这节我们研究下pygame的几种碰撞检测模式:

pygame-KidsCanCode系列jumpy-part17-mask-collide碰撞检测

如上图,左侧是默认的检测模式:基于矩形的检测(这也是性能最好的模式), 右侧是基于圆形的检测(性能略差于矩形检测)。

矩形检测法虽然性能好,但是缺点也很明显:检测不准确,上图中"飞机与目标"从视觉上看,根本没碰到。

为了改进,pygame给这二种模式,新增了xxx_ratio的方法,允许指定检测时,指定二个目标的叠加程度,只有达到指定的叠加值,才认为是真正碰撞到了,参考下图:

pygame-KidsCanCode系列jumpy-part17-mask-collide碰撞检测

注:ratio的值越大,表示叠加的部分越少!

我们写一个小程序来测试一下:

 import pygame
from os import path
from xml.dom.minidom import parse SIZE = (WIDTH, HEIGHT) = (265, 320)
FPS = 45 BLACK = 0, 0, 0
WHITE = 255, 255, 255 pygame.init()
pygame.mixer.init() screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("My Game")
clock = pygame.time.Clock() spritesheet_image_file_name = path.join(path.dirname(__file__), "../img/spritesheet_jumper.png")
spritesheet_xml_file_name = path.join(path.dirname(__file__), "../img/spritesheet_jumper.xml")
spritesheet_image = pygame.image.load(spritesheet_image_file_name)
spritesheet_image.set_colorkey(BLACK)
spritesheet_dom_tree = parse(spritesheet_xml_file_name)
root_textures = spritesheet_dom_tree.documentElement
sub_textures = root_textures.getElementsByTagName("SubTexture")
dic_image = {} def get_image_rect(img_name):
if dic_image.get(img_name):
return dic_image[img_name]
for texture in sub_textures:
name = texture.getAttribute("name")
if img_name == name:
dic_image[img_name] = pygame.Rect(
int(texture.getAttribute("x")),
int(texture.getAttribute("y")),
int(texture.getAttribute("width")),
int(texture.getAttribute("height"))
)
return dic_image[img_name] def get_image(img_name):
rect = get_image_rect(img_name);
image = pygame.Surface((rect.width, rect.height))
image.blit(spritesheet_image, (0, 0), rect)
image.set_colorkey(BLACK)
return image class Demo(pygame.sprite.Sprite):
def __init__(self, image, pos):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = self.image.get_rect()
self.rect.x = pos[0]
self.rect.y = pos[1] running = True
pos1 = (20, 5)
pos2 = (125, 110) demo1 = Demo(get_image("bunny1_walk1.png"), pos1)
demo2 = Demo(get_image("bunny2_stand.png"), pos2) all_sprites = pygame.sprite.LayeredUpdates()
all_sprites.add(demo1, layer=2)
all_sprites.add(demo2, layer=1) group2 = pygame.sprite.Group()
group2.add(demo2) while running:
clock.tick(FPS) for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
demo1.rect.x += -3
if event.key == pygame.K_RIGHT:
demo1.rect.x += 3
if event.key == pygame.K_UP:
demo1.rect.y += -3
if event.key == pygame.K_DOWN:
demo1.rect.y += 3 screen.fill(BLACK) all_sprites.draw(screen) pygame.draw.rect(screen, (0, 255, 0), demo2.rect, 1)
pygame.draw.rect(screen, (255, 0, 0), demo1.rect, 1) font = pygame.font.SysFont("Menlo", 25, True) # 默认的检测模式(rect)
if pygame.sprite.spritecollide(demo1, group2, False):
pos_txt = font.render("hit:true", 1, (255, 255, 128))
else:
pos_txt = font.render("hit:false", 1, (255, 255, 128))
screen.blit(pos_txt, (150, 10)) pygame.display.update() pygame.quit()

pygame-KidsCanCode系列jumpy-part17-mask-collide碰撞检测

这是默认的Rect检测模式。把100行换成:

    # 矩形检测(至少要重叠1-0.7=30%才算发生了碰撞)
if pygame.sprite.spritecollide(demo1, group2, False, pygame.sprite.collide_rect_ratio(0.7)):

再看下效果:

pygame-KidsCanCode系列jumpy-part17-mask-collide碰撞检测

继续,换成圆形检测试下:

    # 圆形检测(至少要重叠1-0.7=30%才算发生了碰撞)
if pygame.sprite.spritecollide(demo1, group2, False, pygame.sprite.collide_circle_ratio(0.7)):

pygame-KidsCanCode系列jumpy-part17-mask-collide碰撞检测

那么,有没有一种方法能做到精确检测呢?当然有,有一种基于mask(在绘图软件中,也称为遮罩或蒙版)的检测方法,类似把背景去掉后,像素级的碰撞检测,当然性能也是最差的。

首先要在Sprite的类上,指定mask:

 class Demo(pygame.sprite.Sprite):
def __init__(self, image, pos):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = self.image.get_rect()
self.rect.x = pos[0]
self.rect.y = pos[1]
#指定蒙版
self.mask = pygame.mask.from_surface(self.image)

然后把检测代码改成:

    # 基于mask的检测
if pygame.sprite.spritecollide(demo1, group2, False, pygame.sprite.collide_mask):

pygame-KidsCanCode系列jumpy-part17-mask-collide碰撞检测

好了,利用上面学到的知识,把上节的遗留问题:"player与enemy的碰撞检测不准确" 解决一下,效果如下:

优化前 优化后
pygame-KidsCanCode系列jumpy-part17-mask-collide碰撞检测 pygame-KidsCanCode系列jumpy-part17-mask-collide碰撞检测

源码示例:https://github.com/yjmyzz/kids-can-code/tree/master/part_17