Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm implementing a camera in my game. It worked for regular objects, but I began using Box2D and obviously things changed a bit. I have a Body object that I want to draw at the center of the screen. Basically what I'm doing is subtracting the viewportX and viewportY from the Body's position.

The relevant code:

public void paint(Graphics2D g, int viewportX, int viewportY) {
    Transform xf = new Transform();

    // m_body is the Body object 

    // Here I attempt to take the transform and alter it by the viewportX and
    // Y, which are something like (-240, -150). It's negative because an
    // object at (500, 300) would be displayed at (160, 150) after the
    // subtraction. DrawUtils.toScale(), is just how I convert units from
    // JBox2D units to my units.
    Vec2 v = Transform.mulTrans(xf, new Vec2(DrawUtils.toScale(-viewportX),

    // Set the new transform to the new vector. Keep the old angle.
    xf.set(v, xf.q.getAngle());

    // I know the following method works correctly. It displays my object,
    // just doesn't follow it.
    for (Fixture f = m_body.getFixtureList(); f != null; f = f.getNext())
        DrawUtils.drawShape(f, xf);

I don't want to alter the actual physics position of the object, just its graphical position such that it's displayed it in the center.

share|improve this question
You shouldn't have your drawing logic tied to your physics data. The drawing data should simply pull positional data from Box2D but be able to render if Box2D didn't exist. Box2D is designed as a simulator and the further you get away from that (teleporting objects around and back to draw them) the more issues you are going to run into. Having both your objects and the Box2D ones are best with your objects simply pulling from the simulated ones Box2D is handling. – ClassicThunder Jul 16 '13 at 13:54
I'm not teleporting anything. Like I said, I'm just drawing it relative to the screen. This is a camera object. Nothing is being moved, the graphical representation is simply being adjusted so that it is in the middle of the screen. – user1264811 Jul 16 '13 at 21:59
up vote 1 down vote accepted

Apparently my method wasn't too far off. Here is the adjustment:

Vec2 n = xf.p.sub(new Vec2(DrawUtils.toScale(-viewportX), DrawUtils
xf.set(n, xf.q.getAngle());
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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