Java – how does libgdx repeat the background?

A few days ago I figured out how to do some scrolling in libgdx Now I'm trying to do something related I want to repeat the background My scrolling follows a ship (an s [ACE ship game]. There is a space photo loaded as a texture in the background. When the ship reaches the end of backgorund, it continues to move forward and has no background. I have read about packaging, but I don't really understand how it works. I did this:

px=new Pixmap(Gdx.files.internal("fondo.jpg"));
    background=new Texture(px);
    background.setWrap(TextureWrap.Repeat,TextureWrap.Repeat);

Then, in my rendering method

spriteBatch.begin();
    spriteBatch.draw(background,500,50);
    drawShip();
spriteBatch.end();

Of course, it doesn't work. It draws the background only once I don't know how to make this packing method work Does it help?

solution

I thought of it This is not a good code, but how it works

First, I declare two textures with the same image

bck1=new Texture(Gdx.files.internal("fondo.jpg"));
 bck2=new Texture(Gdx.files.internal("fondo.jpg"));

I also declare two such variables to specify the x value of each BCK location

int posXBck1=0,posXBck2=0;

Then I use it in render ()

public void calculoPosicionFondos(){
    posXBck2=posXBck1+ANCHODEFONDO;
    if(cam.position.x>=posXBck2+cam.viewportWidth/2){
        posXBck1=posXBck2;
    }
}

where?

Anchodefondo is the width of my background

Cam is otrhocam

So I said if the cam is in bck2 (which means you can't see bck1 again), it changes its position, gives the position of bck2 de bck2, and recalculates bck2 in the next rendering cycle

Then draw two bcks in render mode

Solution

As teitus said, don't load textures multiple times! Anyway, you're on the right track for the wrapping paper:

texture.setWrap(TextureWrap.Repeat,TextureWrap.Repeat);

You can now use the draw method with the source location The source location is the area you choose to paint on the texture

batch.draw(texture,x,y,srcX,srcY,srcWidth,srcHeight)

To scroll the texture from right to left, all you have to do is gradually increase srcx Therefore, create an int that is incremented in the update / render method

int sourceX = 0;

//render() method

//Increment the variable where to draw from on the image.
sourceX += 10;

//Simply draw it using that variable in the srcX.    
batch.draw(YourTexture,sourceX,screenWidth,screenHeight);

Because you are wrapping the texture, it will wrap / loop and scroll indefinitely If the game runs for a long time, sourcex int may have a problem because int can only hold 2147483647 It takes a while, but you can fix it by subtracting the image width every time the number exceeds the total image width

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>