libgdx上的无限滚动背景

时间:2017-12-24 02:10:58

标签: java android libgdx infinite-scroll

我试图在libgdx上做一个无限滚动的背景。图像在X轴上滚动得很好,但是在Y轴上,图像被分成两半,如下图所示。我怎样才能从屏幕底部开始? https://www.w3schools.com/tag_hr

这是我的代码

    package com.tashtoons.game.States;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.tashtoons.game.BuckyRun;
import static com.badlogic.gdx.graphics.Texture.TextureWrap.Repeat;



public class PlaySate extends State {
    private Texture bg;
    float sourceX = 0;

    public PlaySate(GameStateManager gsm) {
        super(gsm);
       bg=new Texture("bg.png");
       cam.setToOrtho(false,BuckyRun.WIDTH/2,BuckyRun.HEIGHT/2);
        bg.setWrap(Repeat,Repeat);
    }

    @Override
    protected void handleInput() {

    }

    @Override
    public void update(float dt) {

    }

    @Override
    public void render(SpriteBatch sb) {
        sourceX += 10;
        sb.setProjectionMatrix(cam.combined);
        sb.begin();
        sourceX = (sourceX + Gdx.graphics.getDeltaTime() / 3/4) % bg.getWidth();
        sb.draw(bg, 0, 0, (int) sourceX, 0,BuckyRun.WIDTH, BuckyRun.HEIGHT);
        sb.end();

    }

    @Override
    public void dispose() {

    }

    }

1 个答案:

答案 0 :(得分:1)

您应该传递到cam.setToOrtho()视口的宽度和高度。 您也可能想要更正用于绘制纹理的代码(代码中的左侧注释):

public class PlaySate extends State {
    private Texture bg;
    float sourceX = 0;

    public PlaySate(GameStateManager gsm) {
        super(gsm);
       bg=new Texture("bg.png");
       cam.setToOrtho(false,BuckyRun.WIDTH,BuckyRun.HEIGHT); // edited this
        bg.setWrap(Repeat,Repeat);
    }


    @Override
    public void render(SpriteBatch sb) {
        sourceX += 10;
        sb.setProjectionMatrix(cam.combined);
        sb.begin();

        // this line doesn't make much sense, you've already incremented sourceX, 
        // "Gdx.graphics.getDeltaTime() / 3/4" especially confuses me
        // why sourceX =% bg.getWidth(); isn't enough?
        sourceX = (sourceX + Gdx.graphics.getDeltaTime() / 3/4) % bg.getWidth();

        // you probably want to draw texture in full screen
        sb.draw(bg,
               // position and size of texture
               0, 0, WIDTH, HEIGHT, 
               // srcX, srcY, srcWidth, srcHeight
               (int) sourceX, 0, bg.getWidth(), bg.getHeight(),
               // flipX, flipY
               false, false);
        sb.end();

    }
}

更新

而不是这两行:

sourceX += 10;
...
sourceX = (sourceX + Gdx.graphics.getDeltaTime() / 3/4) % bg.getWidth();
...

应该只有一个:

sourceX = (sourceX + Gdx.graphics.getDeltaTime() * velocity) % bg.getWidth();