python - 检查一个点是否与pygame中的表面(像素完美)碰撞

标签 python collision-detection pygame

我正在开发一个游戏(一个 missile command 克隆),我需要在其中检查一个 surface (建筑物)与 (导弹)相撞。

screenshot missile command

如何检查导弹是否击中建筑物?

A Rectcollidepoint方法,但我希望它是像素完美的。

scene => 使用 Rect => using rect => 但它应该是像素完美 => want it pixel perfect

最佳答案

您可以使用 Mask并使用它的 get_at方法。

Returns nonzero if the bit at (x,y) is set.

通过调用 pygame.mask.from_surface 创建掩码非常简单

Returns a Mask from the given surface.
Makes the transparent parts of the Surface not set, and the opaque parts set.


因此,给定以下一些向量数学的辅助方法:

def sub(u, v):
  return [ u[i]-v[i] for i in range(len(u)) ]

使用以下代码检查给定点是否在掩膜/表面内:

# 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

关于python - 检查一个点是否与pygame中的表面(像素完美)碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11557314/

相关文章:

python - 在覆盖整个 Canvas 的 python Tkinter Canvas 上绘制矩形不显示顶部和左侧边框

java - 两个类之间如何发生碰撞和 react ?

c# - Unity2D/C# : How do I make a raycast ignore its first collision?

python - 如何在图片上使用pygame set_alpha()

python - 在 Matplotlib 图形窗口中更改图标

python - TypeError : expected str, 字节或 os.PathLike 对象,不是 int;在 subprocess.run()

python - Django 管理仪表板,无法记录 "select all"

android - Unity 2D 与预制件的碰撞无法在手机上运行

python - Pygame逻辑问题

python - 碰撞检测无法正常工作