【问题标题】:Box2D throws error when creating fixture with Polygonshape使用 Polygonshape 创建夹具时 Box2D 抛出错误
【发布时间】:2023-04-11 07:33:02
【问题描述】:

我使用 libGDX。 当我尝试在 Box2D 中创建具有多边形形状的夹具时,出现以下错误。:

java: ./Box2D/Collision/b2Distance.h:103: const b2Vec2& b2DistanceProxy::GetVertex(int32) const: Assertion `0 <= index && index < m_count' failed.

当我不执行 Box2D 的 world.step() 时,我不会再收到此错误。

所以我注释掉了 WorldContactListener 中的所有内容,然后我再次添加了 world.step()。

我仍然遇到同样的错误。

当我用圆形替换多边形时,一切正常。 所以这就是我如何创建我的多边形形状:

 PolygonShape shape = new PolygonShape();

 float ppm = Game.PixelsPerMeter;

 Vector2[] vertices = new Vector2[3];

 vertices[0] = new Vector2(0f/ppm  , 0f  );
 vertices[1] = new Vector2(1/ppm , 1f/ppm  );
 vertices[2] = new Vector2(0f/ppm ,1f/ppm);

 shape.set(vertices);

这就是我如何将所有内容添加到 Box2D 世界:

    float ppm = Game.PixelsPerMeter

    BodyDef bdef = new BodyDef();
    bdef.position.set(100/ ppm,  200/ ppm);
    bdef.type = BodyDef.BodyType.DynamicBody;

    b2dbody = world.createBody(bdef);

    FixtureDef mainFdef = new FixtureDef();


    mainFdef.shape = Shape; //this is the shape from above of course
    b2dbody.createFixture(mainFdef).setUserData(this);

如果你能告诉我怎么了,我会很高兴的!

谢谢

【问题讨论】:

  • ppm的值是多少?
  • @IronMonkey 它是 75
  • 试试 shape.set(vertices, vertices.length);
  • @IronMonkey 谢谢,但是当我这样做时,它会引发以下错误:Error:(382, 17) Gradle: error: no suitable method found for set(Vector2[],int) method PolygonShape.set(Vector2[]) is not applicable (actual and formal argument lists differ in length) method PolygonShape.set(float[]) is not applicable (actual and formal argument lists differ in length) method PolygonShape.set(float[],int,int) is not applicable (actual and formal argument lists differ in length)。没有采用这两个参数的方法。

标签: java libgdx box2d game-engine polygon


【解决方案1】:

更多的是一个疯狂的猜测,但您的 ppm 转换是否正确? 1/ppm(您表示为 75)给出了一个很小的值。我没有深入研究 box2d 代码的内容,但由于它在以米为单位定义对象时效果最佳,因此创建一个顶点为 0,0 和 0,0.0133 (1cm) 的多边形可能会“混淆它”(意味着某种舍入错误或代码中的某处,因此它无法区分顶点并认为至少有 3 个。)

例如,具有 3 个版本的顶点代码的基本应用程序会在前 2 个版本(小值)产生运行时异常,但不会产生较大值的运行时异常:

/*  Version 1 (your code) - Runtime error
vertices[0] = new Vector2(0f/ppm  , 0f  );
vertices[1] = new Vector2(1f/ppm , 1f/ppm  );
vertices[2] = new Vector2(0f/ppm ,1f/ppm);
*/

/* Version 2 (your actual values) - Runtime error
vertices[0] = new Vector2(0f  , 0f  );
vertices[1] = new Vector2(0.0133f , .0133f  );
vertices[2] = new Vector2(0f , 0.0133f);
*/

/* Version 3 (larger values) - No error
vertices[0] = new Vector2(0f  , 0f  );
vertices[1] = new Vector2(1f , 1f  );
vertices[2] = new Vector2(0f ,1f);
*/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多