Box2d夹具位置

3
如何在Libgdx Box2d中获取一个物体的每个fixture的位置? 看起来fixture没有位置getter。如果这个问题很菜,请原谅,因为我刚开始学习Box2d。
2个回答

9

一旦你了解了Transform,这就很容易了。

我们以圆形灯具为例进行演示,因为它们最容易进行演示。

// we need to get the body's position, let's use a Vector2 to store it.
Vector2 vec = new Vector2();
Body body = fixture.getBody();

// what is this magic? Why, it's a wonderful object that transforms fixture
// position information based on the body's position!
Transform transform = body.getTransform();

CircleShape shape = (CircleShape) fixture.getShape();
vec.set(shape.getPosition());
// apply the transformation
transform.mul(vec);
// now vec.x and vec.y will be what you want!

很简单!

但是如果你有一个多边形而不是圆形呢?同样很简单!只需要将变换应用到图形中的每个顶点即可。


这会很好... 但是例如PolygonShape没有getPosition()方法。 - Mars
只是为了“哔”一下。是否有一种简单直接的方法适用于多边形(例如盒子)? - RichieHH
原来PolygonShape有一个getVertex()方法。我找到第一个顶点,将其乘以身体变换,一切都对齐了。我使用setAsBox来配置形状,并使用常规的面向右侧的精灵作为图形组件。 - Max
记住它在Box2d世界中的位置,我曾经为此苦恼了一段时间,因为我忘记了将其从米转换为像素。 - iwek

2

从box2d物体中获取所有fixture的列表。 对于每个fixture,获取其形状。 如果该形状是CircleShape类型,则可以使用getPosition()方法。然而,检索到的位置是相对于b2World中box2d物体的位置。


必须是CircleShape吗?在我的情况下,它是PolygonShape,并且没有getPosition方法。 - Mustafa
为什么需要夹具的位置?可以使用polygonshape的getVertex()方法来解决。 - Abhineet Prasad
2
所以他可以在那里绘制一个精灵。与高级形状上已提供的getPosition相比,getVertex确实是非常低级的。这是他提出的一个不错的问题。 - RichieHH
body.setPosition() 方法会将物体在 b2World 中的位置设置为指定值吗?另外,getPosition() 方法返回的是形状中心点的相对位置还是左上角位置的相对位置? - newguy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接