滚动视差背景,在libgdx中无限重复

时间:2011-09-22 11:15:39

标签: scroll 2d textures libgdx parallax

我正在制作2D侧面太空射击游戏,我需要一个可以无限滚动的背景(它是平铺或重复包裹)。我也想实现视差滚动,所以可能有一个最低的背景星云纹理几乎没有移动,更高的一个包含几乎没有移动的远处星星,最高的背景包含移动很多的近星。

我从谷歌看到我的每一层移动比它上面的层少50%,但我如何在libgdx中实现这一点?我有一个可以放大和缩小的相机,在物理800x480屏幕上可以显示从128x128像素(一艘船)到大面积空间的任何东西,其边缘纹理包裹多次。

如何连续包裹较小的纹理(比如说512x512),好像它是无限平铺的(当相机直接缩小时),然后如何将多个纹理分层,将它们组合在一个合适的结构中(在libgdx api中有一个吗?)并随着玩家的坐标改变而移动它们?我看过javadocs和示例,但找不到类似这个问题的任何内容,如果这很明显就道歉!

4 个答案:

答案 0 :(得分:10)

嘿,我也在制作一个parrallax背景,试图让它滚动。

存储库中有一个ParallaxTest.java,可以找到here

此文件是一个独立的类,因此您需要将其合并到游戏中。并且您需要更改控制输入,因为它已连接到使用触摸屏/鼠标。

这对我有用。至于重复的bg,我还没有到目前为止,但我认为你只需要基本的逻辑,好一个屏幕远离结束,改变前几个屏幕pos最后排队。

答案 1 :(得分:3)

关于视差滚动,我没有比PFG更多的说法了。测试文件夹下的存储库中确实存在一个示例,并且网络上有几个解释。我喜欢this one。 背景问题很容易解决。通过使用模块代数可以解决这个问题和其他相关问题。我不会详细介绍,因为一旦显示就很容易理解。

想象一下,您想在屏幕上显示指南针。你有一个纹理1024x16代表基数点。基本上你只有一个条带。暂且不考虑真正的方向等等,你必须渲染它。

例如,您的视口为300x400,并且您希望屏幕上有200px的纹理(以使其更有趣)。您可以使用单个区域完美渲染它,直到到达位置(1024-200)= 824.一旦您处于此位置,则无法再显示纹理。但由于它是一个指南针,很明显,一旦你到达它的末尾,它必须重新开始。所以这就是答案。另一个纹理区域将起到作用。范围825-1023必须由另一个区域代表。第二区域的大小为(1024-pos),每个值pos> 824&& pos< 1024

此代码旨在作为指南针的真实示例。由于范围(0-3.6)到(0-1024)之间的转换,它非常脏,因为它始终与相对位置一起工作。

spriteBatch.begin();
    if (compassorientation<0)
        compassorientation = (float) (3.6 - compassorientation%3.6);
    else
        compassorientation = (float) (compassorientation %  3.6);
    if ( compassorientation < ((float)(1024-200)/1024*3.6)){
        compass1.setRegion((int)(compassorientation/3.6*1024), 0, 200, 16);
        spriteBatch.draw(compass1, 0, (Gdx.graphics.getHeight()/2) -(-250 + compass1.getTexture().getHeight()* (float)1.2), Gdx.graphics.getWidth(), 32 * (float)1.2);

    }
    else if (compassorientation > ((float)(1024-200)/1024*3.6)) {
        compass1.setRegion((int)(compassorientation/3.6*1024), 0, 1024 - (int)(compassorientation/3.6*1024), 16);
        spriteBatch.draw(compass1, 0, (Gdx.graphics.getHeight()/2) -(-250 + compass1.getTexture().getHeight()* (float)1.2), compass1.getRegionWidth()/200f * Gdx.graphics.getWidth() , 32 * (float)1.2);
        compass2.setRegion(0, 0, 200 - compass1.getRegionWidth(), 16);
        spriteBatch.draw(compass2, compass1.getRegionWidth()/200f * Gdx.graphics.getWidth() , (Gdx.graphics.getHeight()/2) -(-250 + compass1.getTexture().getHeight()* (float)1.2), Gdx.graphics.getWidth() - (compass1.getRegionWidth()/200f * Gdx.graphics.getWidth())  , 32 * (float)1.2);
    } 


    spriteBatch.end();

答案 2 :(得分:1)

你可以使用如下的setWrap函数:

Texture texture = new Texture(Gdx.files.internal("images/background.png"));
texture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);

它会反复绘制背景!希望这有帮助!

答案 3 :(得分:1)

在您为对象初始化纹理的位置下方。然后在这个

中的那个类型下面
YourTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);

你的纹理是你希望视差滚动的纹理。

在您的渲染文件中输入此代码。

batch.draw(YourTexture,0, 0, 0 , srcy, Gdx.graphics.getWidth(),     
           Gdx.graphics.getHeight());  
srcy +=10;

它会给你一个错误,所以创建一个名为srcy的变量。这没什么太花哨的。

Int srcy
相关问题