目标:实现完美的碰撞检查
前面的只是普通的碰撞检查,用到了矩形框的范围。图像如果都不是矩形,用普通检查,两种已经相碰,但画面显示还未相碰,这就很尴尬了。
sprite模块中,有个collide_mask()函数可以利用。
ygame.sprite.
collide_mask
()
Collision detection between two sprites, using masks.
collide_mask(SpriteLeft, SpriteRight) -> point
Returns first point on the mask where the masks collided, or None if there was no collision.
Tests for collision between two sprites, by testing if their bitmasks overlap. If the sprites have a "mask" attribute, that is used as the mask, otherwise a mask is created from the sprite image. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "mask" attribute.
You should consider creating a mask for your sprite at load time if you are going to check collisions many times. This will increase the performance, otherwise this can be an expensive function because it will create the masks each time you check for collisions.
sprite.mask = pygame.mask.from_surface(sprite.image)
简单的翻译下,被检查对象要有mask属性,用于检查的范围。pygame还有专门的mask模块, from_surface()可以将Surface对象中的非透明部分表示为mask并返回。
在对象中定义
self.mask = pygame.mask.from_surface(self.image) #类要继承至sprite
碰撞检查的函数改为:
beshoted = pygame.sprite.spriteco