5
\$\begingroup\$

I'm moving from Qt Widgets' QGraphicsScene to Qt Quick's QQuickItem for rendering my game objects. One of the things this involves is setting up a scene and the view onto that scene, as this was previously managed by QGraphicsScene and QGraphicsView.

My naive attempt was to do the following:

void SceneView::centerOn(const QPointF &pos)
{
    if (mScene) {
        mScene->setX(-(pos.x() - width() / 2));
        mScene->setY(-(pos.y() - height() / 2));
    }
}

This works, but it produces this odd effect where some game objects "jump around" between neighbouring pixels while the camera comes to a halt while following the player:

bad

The player's movement is fine. The crate also does not seem to exhibit this problem (though its Box2D debug drawing marker does).

This is what it looks like when the player moves without the camera following it:

good, sorta

This is what I'd expect from the other game objects when the camera is moving; no movement whatsoever relative to the scene.

The old, correct movement looked like this:

correct

The old code:

void MapView::centerOverFollowedItem()
{
    QRectF geometry(mFollowing->pos(), mFollowing->boundingRect().size());
    centerOn(geometry.center());
}

(QGraphicsView::centerOn implementation)

What could be causing this?

\$\endgroup\$
9
\$\begingroup\$

Ok, that's awkward. My last edit revealed the answer to my problem (that I've been struggling with all day): QGraphicsView casts the camera x/y position to integers...

This is the solution:

void SceneView::centerOn(const QPointF &pos)
{
    if (mScene) {
        mScene->setX(int(-(pos.x() - width() / 2)));
        mScene->setY(int(-(pos.y() - height() / 2)));
    }
}
\$\endgroup\$
  • 9
    \$\begingroup\$ +1 The rubber duck strikes again! :) \$\endgroup\$ – Anko Aug 23 '15 at 14:13
  • 2
    \$\begingroup\$ It would be so less humiliating if I just used a rubber duck instead. :p \$\endgroup\$ – Mitch Aug 23 '15 at 14:18
  • 3
    \$\begingroup\$ Don't feel bad—it happens to everyone. (Here's me a few months back.) I edited the title so people of the future can hopefully find this more easily. \$\endgroup\$ – Anko Aug 23 '15 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.