How to make an infinite scrolling background?

:bust_in_silhouette: Reply From: ddabrahim

I managed to create an infinite scrolling background.

Instead of moving and swapping 2 images to create the effect, I decided to set the image to “Repeat” in the import properties and then used the Region property of the sprite class to create a tiled sprite from the background as shown in this tutorial:
http://kidscancode.org/blog/2017/04/godot_101_12/

Then what I did is move the sprite to the left and when the origin point of the sprite (the middle of the Region) is about to leave the screen on the left I simply reset the position of the sprite back to the original and continue move to the left. The result is an infinite scrolling background effect.

This is my solution, but in case anyone have any better idea how to go about this, please share.

Thanks.

hey,
I’ve been trying out working with shaders recently and just managed to succeed creating an infinite scrolling background without using a Camera and just a few lines of shader code. I thought this might be helpful to someone maybe…

So, I added my background texture to a sprite (make sure you set “Repeat” to Enabled in the Import section, just as mentioned above).
Then I added a new Shader Material to the sprite and added a new shader to that with the following code:

shader_type canvas_item;

uniform vec2 direction = vec2(1.0,0.0);
uniform float speed_scale = 0.05;

void fragment(){

     vec2 move = direction * TIME * speed_scale;

     COLOR = texture(TEXTURE, UV + move);	
}

now my background is infinitly moving to the left. Because of the “uniform” keyword you can simply adjust the direction and speed in the editor or through the gdscript of the Sprite, by using

material.set_shader_param("direction", Vector2(0.0,1.0))
material.set_shader_param("speed_scale",0.02)

Hope this helps

savetheflave | 2019-04-25 19:45