转换为世界坐标时奇数Box2D错误

时间:2014-09-27 08:10:58

标签: python python-2.7 box2d game-physics physics-engine

我写了一个函数来使用pygame绘制我的Box2D框,但是在我通过body的变换将框的顶点向量相乘的步骤中,程序崩溃了。

这是功能:

def draw(self):
    pointlist = []
    for vertex in self.fixture.shape.vertices:
        vertex = vec2(vertex[0], vertex[1])
        print vertex, self.body.transform
        vertex * self.body.transform
        pointlist.append(world_to_screen(
            vertex[0],
            vertex[1]
            ))
    pygame.draw.polygon(SCREEN, RED, pointlist)

以下是我收到的错误:

b2Vec2(-0.4,-0.4) b2Transform(
    R=b2Mat22(
            angle=0.0,
            col1=b2Vec2(1,0),
            col2=b2Vec2(-0,1),
            inverse=b2Mat22(
                        angle=-0.0,
                        col1=b2Vec2(1,-0),
                        col2=b2Vec2(0,1),
                        inverse=b2Mat22((...) )
    angle=0.0,
    position=b2Vec2(6,5.99722),
    )
Traceback (most recent call last):
...
line 63, in draw
    vertex * self.body.transform
TypeError: in method 'b2Vec2___mul__', argument 2 of type 'float32'
[Finished in 2.4s with exit code 1]

我不明白。我正在通过self.body.transform.__mul__()似乎是有效的论据,变换和向量,但它给出了一个我不理解的奇怪错误。

1 个答案:

答案 0 :(得分:1)

您尝试将顶点与矩阵相乘。这不受支持,反过来试试:

transform * vertex

此外,您不必要地复制,但不会分配应用转换的结果。

这应该有效:

def draw(self):
    pointlist = []
    for vertex in self.fixture.shape.vertices:
       transformed_vertex = vertex * self.body.transform
       pointlist.append(world_to_screen(
          transformed_vertex[0],
          transformed_vertex[1]
          ))
    pygame.draw.polygon(SCREEN, RED, pointlist)

我还建议你让你的world_to_screen采用顶点,从而使整个事件变得简单

def draw(self):
    t = self.body.transform
    pointlist = [w2s(t * v) for v in self.fixture.shape.vertices]
    pygame.draw.polygon(SCREEN, RED, pointlist)