【问题标题】:Box2D center of rotationBox2D 旋转中心
【发布时间】:2013-12-28 01:50:57
【问题描述】:

我使用 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 中设置原点?

【问题讨论】:

    标签: c++ graphics 2d box2d qml


    【解决方案1】:

    为了保持代码简单,并且因为qml-box2d 是一个未完成的库,transformOrigin 设置为TopLeftBody 的默认值)是当前唯一受支持的值。

    但是,Box2D 主体本身不需要有大小。只有其固定装置的大小是相关的。如果您在主体上设置 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 的所有可能值,而不管正文的大小。

    【讨论】:

      猜你喜欢
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多