Box2d libgdx, a bit confused about the pixels to meters stuff

前端 未结 1 757
情歌与酒
情歌与酒 2021-01-24 08:06

So I understand the concept. The idea is that box2d more or less works in meters, so you need to do a conversion from pixels to it. Makes sense. I was following the tutorial/int

1条回答
  •  执笔经年
    2021-01-24 08:37

    I do like you are doing but might be a little different.

    Might be a little overkill but here's my jucl port

    jucl/Android - pastebin

    Then I just have utility classes ie:

    public class Pixel {
    
        public static float toMeter(float pixels) {
            return (float)LengthConversions.Pixel2SIf(pixels);
        }
    
        public static Vector2 toMeter(Vector2 vecPixel) {
            return new Vector2(Pixel.toMeter(vecPixel.x), Pixel.toMeter(vecPixel.y));
        }
    }
    
    public class Meter {
    
        public static final float METERS_PER_PIXEL = (float) LengthConversions.SI_PIXEL;
    
        public static float toPixel(float meter) {
            return (float)LengthConversions.SI2Pixelf(meter);
        }
    }
    

    In my initialize:

    int graphicsWidth = Gdx.graphics.getWidth();
    int graphicsHeight = Gdx.graphics.getHeight();
    
    CAMERA_WIDTH_METERS = Pixel.toMeter(graphicsWidth);
    CAMERA_HEIGHT_METERS = Pixel.toMeter(graphicsHeight);
    

    Then in my game classes (like your Player class). In my case it was a pinball game so i have Flipper, Ball, Bumper, etc. I have a @Override render() method where I sync up the sprite with the physics body.

    Here's an example file..sry it's messy but might be helpful.

    Pinball Engine Class file

    0 讨论(0)
提交回复
热议问题