box2d b2PolygonShape顶点索引随机变化

时间:2019-07-09 17:40:58

标签: python box2d

在Python中创建b2PolygonShape时,我意识到代码中的错误似乎归因于顶点的变化。

假设您要创建一个简单的三角形,其顶点为[(0, 0), (1, 0), (0, 1)]。根据文档,您需要以CCW方式定义顶点,我已经从(0, 0)开始了。

In [57]: triangle = b2PolygonShape(vertices=[(0,0), (1,0), (0,1)])

In [58]: triangle
Out[58]: b2PolygonShape(vertices: [(1.0, 0.0), (0.0, 1.0), (0.0, 0.0)])

那为什么在设置顶点时它们会改变?

另一个例子:

In [62]: verts = [(0, 0), (1, 0), (1, -1), (0, -1)]

In [63]: square = b2PolygonShape(vertices=verts)

In [64]: square
Out[64]: b2PolygonShape(vertices: [(1.0, -1.0), (1.0, 0.0), (0.0, 0.0), (0.0, -1.0)])

这对我来说是个问题:假设我们拥有一个正方形,并且希望根据原点(0, 0)将其旋转10度。

In [70]: import math
In [71]: def deg2rad(degree):
    ...:     return degree * math.pi / 180.
    ...:
In [74]: def rotate_poly(coords, center, angle):
    ...:     rads = deg2rad(angle)
    ...:     new_coords = []
    ...:     for coord in coords:
    ...:         new_coord = b2Vec2()
    ...:         new_coord.x = math.cos(rads)*(coord.x - center.x) - math.sin(rads)*(coord.y - center.y) + center.x
    ...:         new_coord.y = math.sin(rads)*(coord.x - center.x) + math.cos(rads)*(coord.y - center.y) + center.y
    ...:         new_coords.append(new_coord)
    ...:
    ...:     return new_coords
    ...:
In [81]: verts = [b2Vec2(coord[0], coord[1]) for coord in verts]

In [82]: verts
Out[82]: [b2Vec2(0,0), b2Vec2(1,0), b2Vec2(1,-1), b2Vec2(0,-1)]

现在看看旋转顶点时会发生什么:

In [83]: rotate_poly(verts, b2Vec2(0,0), 10)
Out[83]:
[b2Vec2(0,0),
 b2Vec2(0.984808,0.173648),
 b2Vec2(1.15846,-0.81116),
 b2Vec2(0.173648,-0.984808)]

注意我的原籍(0, 0)如何保持在同一位置

现在看看将square旋转10时会发生什么:

In [85]: square = b2PolygonShape(vertices=rotate_poly(verts, b2Vec2(0, 0), 10))

In [86]: square
Out[86]: b2PolygonShape(vertices: [(1.1584559679031372, -0.8111595511436462), (0.9848077297210693, 0.1736481785774231), (0.0, 0.0), (0.1736481785774231, -0.9848077297210693)])

请注意,我的原点(0, 0)现在在顶点列表中的索引2是什么。

现在看看当我将square旋转-10时会发生什么:

In [87]: square = b2PolygonShape(vertices=rotate_poly(verts, b2Vec2(0, 0), -10))

In [88]: square
Out[88]: b2PolygonShape(vertices: [(0.9848077297210693, -0.1736481785774231), (0.0, 0.0), (-0.1736481785774231, -0.9848077297210693), (0.8111595511436462, -1.1584559679031372)])

请注意,我的原籍(0, 0)现在是如何在索引1上找到的。

似乎没有原因。我希望我添加顶点的顺序成为它们保留的顺序。当我尝试获取原点时,这变得很成问题,因为我必须在索引列表中进行搜索。有什么理由会发生这种情况吗?关于顶点的设置,我是否不了解?

In [99]: Box2D.__version__
Out[99]: '2.3.2'

0 个答案:

没有答案