在Body上绘制精灵 - 相机查看端口并调整

时间:2016-11-17 20:58:11

标签: libgdx box2d

我用这种方法(在我的身体包装内)画出精灵的身体:

private void drawBaseSprite(Batch batch){
        Sprite baseSprite = this.getBaseSprite();

        Vector3 bodyPixelPos = camera.project(new Vector3(body.getPosition().x, body.getPosition().y, 0));

        // TODO: 17/11/16 Review this
        float w = scale * (baseSprite.getTexture().getWidth())/camera.zoom;
        float h = scale * (baseSprite.getTexture().getHeight())/camera.zoom ;

        baseSprite.setSize(w,h);
        baseSprite.setOrigin(w/2, h/2);
        baseSprite.setPosition(bodyPixelPos.x -w/2, bodyPixelPos.y - h/2);
        baseSprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);


        baseSprite.draw(batch);
    }

一切都很好,直到我尝试调整窗口大小。好吧,我跟着这个调整大小的逻辑(实现屏幕):

@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height, true);
    stage.camera.setToOrtho(false, Constants.VIEWPORT_HEIGHT *width/(float)height, Constants.VIEWPORT_HEIGHT);
}

调整大小之前: before resize 调整大小(更大的宽度): after resize (larger width)

我发现这很荒谬,因为:

        float w = scale * (baseSprite.getTexture().getWidth())/camera.zoom;
        float h = scale * (baseSprite.getTexture().getHeight())/camera.zoom ;

不会改变,而图像是x缩放的。

2 个答案:

答案 0 :(得分:0)

我是否理解您的问题是图像不能保持在身体顶部?

如果是这样,之所以不这样做是因为你要设置图像相对于相机的尺寸,而不是它应该覆盖的身体。当您更改相机的变焦时,您可以调整图像的大小,但不能调整身体的大小,并且它们会不同步。

我建议您更改逻辑,使图像高度/宽度完全由身体确定,并根据相机缩放比例缩放您的身体。

答案 1 :(得分:0)

嗯,这解决了我的问题,但我仍然不知道为什么。

private void drawBaseSprite(Batch batch){
        Sprite baseSprite = this.getBaseSprite();
        batch.setProjectionMatrix(camera.combined);
        float someScale = 0.1f;

        float w = scale * (baseSprite.getTexture().getWidth())/camera.zoom *someScale;
        float h = scale * (baseSprite.getTexture().getHeight())/camera.zoom *someScale;


        Vector3 bodyPixelPos = camera.project(new Vector3(body.getPosition().x, body.getPosition().y, 0))
                .scl(someScale*camera.viewportHeight/(Gdx.graphics.getHeight()/20f)).sub(w/2, h/2, 0);

        baseSprite.setSize(w,h);
        baseSprite.setOrigin(w/2, h/2);
        baseSprite.setPosition(bodyPixelPos.x, bodyPixelPos.y);
        baseSprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);

        baseSprite.draw(batch);
    }