Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

By now i have this Camera class.

package GameObjects;


import main.Main;

import org.jbox2d.common.Vec2;
public class Camera {

public int x;
public int y;
public int sx;
public int sy;

public static final float PIXEL_TO_METER = 50f;

private float yFlip = -1.0f;

public Camera()
{
    x = 0;
    y = 0;
    sx = x + Main.APPWIDTH;
    sy = y + Main.APPHEIGHT;
}

public Camera(int x, int y)
{
    this.x = x;
    this.y = y;
    sx = x + Main.APPWIDTH;
    sy = y + Main.APPHEIGHT;
}

public void update()
{
    sx = x + Main.APPWIDTH;
    sy = y + Main.APPHEIGHT;
}

public void moveCam(int mx, int my)
{

    if(mx >= 0 && mx <= 80)
    {
        this.x -= 2;
    } else if(mx <= Main.APPWIDTH && mx >= Main.APPWIDTH - 80)
    {
        this.x += 2;
    }

    if(my >= 0 && my <= 80)
    {
        this.y += 2;
    } 
    else if(my <= Main.APPHEIGHT && my >= Main.APPHEIGHT - 80)
    {
        this.y -= 2;
    }
    this.update();
}

public float meterToPixel(float meter)
{
    return meter * PIXEL_TO_METER;
}

public float pixelToMeter(float pixel)
{
    return pixel / PIXEL_TO_METER;
}

public Vec2 screenToWorld(Vec2 screenV) {
    return new Vec2(screenV.x + this.x, yFlip
            * screenV.y + this.y);
}

public Vec2 worldToScreen(Vec2 worldV) {
    return new Vec2(worldV.x - this.x, yFlip
            * worldV.y - this.y);
}

}

I need to know how to modify the screenToWorld and worldToScreen functions to include the PIXEL_TO_METER scaling.

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

I've managed to do this myself. Here is what everyone who has the same problem should do:

public Vec2 screenToWorld(Vec2 screenV) {
    return new Vec2( this.x + screenV.x / PIXEL_TO_METER, yFlip
            * (screenV.y / PIXEL_TO_METER + this.y));
}

public Vec2 worldToScreen(Vec2 worldV) {
    return new Vec2((worldV.x - this.x) * PIXEL_TO_METER, (yFlip
            * worldV.y - this.y) * PIXEL_TO_METER);
}
share|improve this answer
1  
Thanks Romeo. this is very helpful. can you tell me the meaning of the variable "yFlip"? i don't understand why it's declared as float. –  user15522 Apr 19 '12 at 17:26
    
Sorry for responding so late. You will understand from here: shiffman.net/itp/classes/nature/box2d_2010/worlds.jpg . As you can see in the Box2D world y is incremented by going up. Well, in the screen world the y is incremented by going down. So you need to transform that value using the yFlip and is declared by float because i need to multiply it to another float value without doing any conversion. –  Romeo Apr 23 '12 at 14:39
add comment

Your Answer

 
discard

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.