libgdx上的无限滚动背景

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了libgdx上的无限滚动背景相关的知识,希望对你有一定的参考价值。

我试图在libgdx上做一个无限滚动的背景。图像在X轴上滚动很好,但是在Y轴上,图像被分成两半,如下图所示。我怎样才能从屏幕底部开始? enter image description here

这是我的代码

    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() {

    }

    }
答案

你应该传递给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();

以上是关于libgdx上的无限滚动背景的主要内容,如果未能解决你的问题,请参考以下文章

精灵上的无限滚动(视差)

如何为无限滚动的 RecyclerView 绘制背景

SpriteKit 中的无限滚动背景

2d场景背景无限滚动

unity 背景无限循环滚动效果

在无限滚动Wordpress帖子中包含脚本