我使用 Box2D 作为物理引擎,使用 QtQuick 作为可视化工具。
我设置了一个简单的场景,其中有下落的小矩形和平台来测试碰撞
// the platform block
Body {
id: block
bodyType: Body.Kinematic
width:200
height:20
transformOrigin: Body.Center
fixtures: Box {
anchors.fill: parent
friction: 1
density: 1
}
Rectangle {
anchors.fill: parent
color: "yellow"
border.color: "blue"
}
MouseArea {
anchors.fill: parent
onClicked: {
block.rotation += 20
}
}
}
在 QML 中我可以设置旋转中心:
transformOrigin: Body.Center
默认情况下,transformOrigin 是对象的左上角,在这种情况下一切都很好。但是当我在 QML 中将原点移动到中心时,它会出错,如附图中所述
这是从 Box2D 获取坐标并绘制 QML 对象时的部分代码
//getting coordination and angle of Box2D object
const b2Vec2 position = mBody->GetPosition();
const float32 angle = mBody->GetAngle();
const qreal newX = position.x * scaleRatio;
const qreal newY = -position.y * scaleRatio;
const qreal newRotation = -(angle * 360.0) / (2 * b2_pi);
// paint QML object at received coords
setX(newX);
setY(newY);
setRotation(newRotation);
问题在于 Box2D 旋转的对象原点位于左上角,而 QML 对象的原点位于其中心。所以 QML 对象没有与 Box2D 和错误位置的下降矩形画家同步。我制作了 printscreen 但实际上 Box2D 的框是不可见的,我添加它是为了了解问题。
我的问题 - 如何在 Box2D 中设置原点?
最佳答案
保持代码简单,因为qml-box2d是一个未完成的库,transformOrigin
设置为 TopLeft
(Body
的默认设置)是目前唯一受支持的值。
但是,Box2D 主体本身不需要尺寸。只有其固定装置的大小是相关的。如果您在 body 上设置 0 大小,则它的 transformOrigin
不再重要。如果您随后将夹具置于主体的中心,主体的旋转将有效地应用到夹具的中心。
我已经使用这种方法调整了您的简单场景,如下所示:
// the platform block
Body {
id: block
bodyType: Body.Kinematic
fixtures: Box {
id: boxFixture
anchors.centerIn: parent
width:200
height:20
friction: 1
density: 1
}
Rectangle {
anchors.fill: boxFixture
color: "yellow"
border.color: "blue"
}
MouseArea {
anchors.fill: boxFixture
onClicked: {
block.rotation += 20
}
}
}
当然,理想情况下 qml-box2d 最终会处理 transformOrigin
的所有可能值,而不管主体的大小。
关于c++ - Box2D 旋转中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20810176/