pymunk space.remove方法出错

时间:2013-03-07 10:23:11

标签: python pygame pymunk

我有一个球生成器,它“生成”并将球(圆圈)添加到模拟中。

当球击中列表s_boxes中的静态多边形时,球将被移除 这是由碰撞处理程序ball_wall_collision完成的。

错误:
以下弹出窗口显示其名称所示,弹出窗口 **POP UP WINDOW**

我的代码:
球发生器

class BallGenerator:
    def __init__(self, min_y, max_y, x):
        self.min = min_y
        self.max = max_y
        self.x = x

        self.counter = 0

    def bowl(self, balls):
        global ball_bowled
        y = random.randint(self.min, self.max)
        pos = to_pymunk((self.x,y))
        r = 10
        m = 15
        i = pm.moment_for_circle(m, 0, r)
        b = pm.Body(m,i)
        b.position = pos
        f_x = random.randint(-600000,-400000)
        b.apply_force( (f_x,0.0),(0,0) )

        ball = pm.Circle(b, r)
        ball.elasticity = 0.75
        ball.friction = 0.95
        balls.append(ball)
        space.add(ball,b)
        print 'bowled'

        ball_bowled += 1

    def handle(self, balls):
        if self.counter == FPS:
            self.bowl(balls)
            self.counter = 0
        self.counter += 1

碰撞处理程序

def ball_wall_collision(space, arb, balls, s_boxes):
    shapes = arb.shapes
    boxes = [box[0] for box in s_boxes] # Get walls
    ball = None
    wall = None
    for ba in balls:
        if ba in shapes:
            ball = ba
            break
    for box in boxes:
        if box in shapes:
            wall = box
            break
    if wall and ball:
        print 'removing'
        space.remove(ball, ball.body) # Where the runtime problem happens
        balls.remove(ball)
        print 'removed'

        return False
    else:
        return True
space.add_collision_handler(0,0,begin=ball_wall_collision,
                            balls=balls,s_boxes=s_boxes) # Other args to function

碰撞处理中我做错了什么?

  • 我在space.remove的电话中遗漏了什么?
  • 这个功能是不是我想要的? 或者是其他地方的错误(我认为不是这样)......

1 个答案:

答案 0 :(得分:2)

看起来问题是您在模拟步骤中尝试从碰撞处理程序中的空间中删除对象。

相反,您可以尝试手动将所有球收集到一个列表中,然后在步骤后调用remove,或者使用post step回调删除队列,如下所示:

space.add_post_step_callback(space.remove, ball)
space.add_post_step_callback(space.remove, ball.body)

(未经测试的代码)

我应该尝试在API文档中使这一点更加明显..我想知道自动安排删除直到步骤结束,或者介入性较小的选项,在python中触发断言是否是个好主意所以你不要得到c ++错误。

相关问题