首页 > 解决方案 > 有没有办法使用颜色在 PyGame 中的形状之间进行碰撞?

问题描述

当形状接触特定颜色时,有没有办法在 pygame 中进行碰撞。就像以某种方式控制形状(例如:弹力球、移动形状等)时,是否有办法检测到它接触了特定类型的颜色?

标签: pythonpygamecollision-detection

解决方案


是的,您可以,这里有一个来自 sentdex 链接的示例:https ://pythonprogramming.net/detecting-collisions-intermediate-python-tutorial/

def is_touching(b1,b2):
    return np.linalg.norm(np.array([b1.x,b1.y])-np.array([b2.x,b2.y]))< (b1.size + b2.size)


def handle_collisions(blob_list):
    blues, reds, greens = blob_list
    for blue_id, blue_blob in blues.copy().items():
        for other_blobs in blues, reds, greens:
            for other_blob_id, other_blob in other_blobs.copy().items():
                if blue_blob == other_blob:
                    pass
                else:
                    if is_touching(blue_blob, other_blob):
                        blue_blob + other_blob
                        if other_blob.size <= 0:
                            del other_blobs[other_blob_id]
                        if blue_blob.size <= 0:
                            del blues[blue_id]
                            
    return blues, reds, greens


推荐阅读