slo*_*oth 2 python pygame collision-detection
我正在开发一种游戏(导弹命令克隆),我需要检查一个surface(建筑物)是否与point(导弹)发生碰撞.

如何检查导弹是否撞击建筑物?
A Rect有这个collidepoint方法,但我希望它是像素完美的.
=>使用a Rect=>
=>但它应该是像素完美=> 
如果设置了(x,y)的位,则返回非零值.
通过调用来创建掩码非常简单 pygame.mask.from_surface
从给定曲面返回一个Mask.
使Surface的透明部分不设置,并设置不透明部分.
因此,给出了一些矢量数学的辅助方法:
def sub(u, v):
return [ u[i]-v[i] for i in range(len(u)) ]
Run Code Online (Sandbox Code Playgroud)
使用以下代码检查给定点是否在掩码/表面内:
# create mask from surface
mask = pygame.mask.from_surface(building.surface)
# translate the position of the missile,
# since the top left coordinate of the mask is always (0, 0)
rel_point = sub(missile.position, building.position)
try:
if mask.get_at(rel_point):
# point in mask
do_something()
except IndexError:
pass
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1875 次 |
| 最近记录: |