You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何在Pymunk中无需创建类实现子弹与边界线碰撞检测?

子弹与屏幕边界线的碰撞检测解决方案

问题描述

需要检测子弹与用于阻止玩家移出屏幕的边界线是否发生碰撞,现有边界线创建代码、碰撞处理代码,但尝试自定义类实现碰撞类型设置未生效,希望避免自定义类完成需求。

现有边界线创建代码

def create_lines():
    """Prevent objects from moving out of the screen"""
    static_lines = [
        pymunk.Segment(space.static_body, (0,0), (current_map.width,0), 0.0),
        pymunk.Segment(space.static_body, (current_map.width,0), (current_map.width,current_map.height), 0.0),
        pymunk.Segment(space.static_body, (current_map.width,current_map.height), (0,current_map.height), 0.0),
        pymunk.Segment(space.static_body, (0,current_map.height), (0,0), 0.0)]
    space.add(static_lines)

现有碰撞处理代码

def collision_bullet_line(arb, space, data):
    bullet = arb.shapes[0]
    line   = arb.shapes[1]
    
    print('collision line!!')

handler = space.add_collision_handler(1, 5)
handler.pre_solve = collision_bullet_line

未生效的自定义类尝试

class Line(GamePhysicsObject):
    """ This class extends the GamePhysicsObject to handle box objects. """

    def __init__(self, x, y, sprite, space):
        super().__init__(x , y, 0, sprite, space)
        self.shape.collision_type = 5

解决方案

不需要自定义类,直接给创建的pymunk.Segment实例设置collision_type属性即可,修改create_lines函数如下:

def create_lines():
    """Prevent objects from moving out of the screen"""
    static_lines = [
        pymunk.Segment(space.static_body, (0,0), (current_map.width,0), 0.0),
        pymunk.Segment(space.static_body, (current_map.width,0), (current_map.width,current_map.height), 0.0),
        pymunk.Segment(space.static_body, (current_map.width,current_map.height), (0,current_map.height), 0.0),
        pymunk.Segment(space.static_body, (0,current_map.height), (0,0), 0.0)
    ]
    # 为每个边界线设置碰撞类型为5
    for line in static_lines:
        line.collision_type = 5
    space.add(static_lines)

关键说明

  1. 原自定义类未生效的原因:创建边界线时直接使用了pymunk.Segment,并未实例化自定义的Line类,所以类内的碰撞类型设置根本没作用到边界线上。
  2. 修改后的代码通过循环给每个线段设置collision_type=5,与你配置的碰撞处理器(类型1和5)匹配,子弹与边界线碰撞时就能正常触发collision_bullet_line函数。

内容的提问来源于stack exchange,提问作者Bart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:25:26