I just wanted to make the same effect, but couldn't find something on the internet, so I am writing a little tutorial here, it is not that hard to make.
Lets set up the nodes first, you need a ParallaxBackground
and two ore more ParallaxLayer
as child nodes and each ParallaxLayer
needs a Sprite
as child. Give the first Sprite
the background texture, the second Sprite
the foreground texture.
Next you need to get the x and y coordinates of your mouse, that is possible with
func _input(event):
if event is InputEventMouseMotion:
var mouse_x = event.position.x
var mouse_y = event.position.y
Next you want to map the mouse coordinates on the screen between the intervall
[-1 1].
For this you need the size of your screen, you can get that with get_viewport.size()
, there are many other ways to get the size of your screen, you may use what suits you best.
Then you can do
var relative_x = (mouse_x - (viewport_size.x/2)) / (viewport_size.x/2)
var relative_y = (mouse_y - (viewport_size.y/2)) / (viewport_size.y/2)
Now you have the positon of your mouse relative to the middle of the screen, which is 0 in the middle 1 at the far right/down and -1 at the far left/up, perfect!
Whats left to do is to manipulate the position of the ParallaxLayers, just get the node for each ParallaxLayer and set the motion_offset
property like this:
ParallayLayer.motion_offset.x = multiplier * relative_x
ParallayLayer.motion_offset.y = multiplier * relative_y
multiplier
is a value that amplifies the parallax effect, use smaller values for background layers and greater values for foreground layers, but it should be at least 2, to have a visible effect.
So thats it!
The ParallaxLayers need to update every time the mouse moves so all that code goes into the func _input(event):
To avoid that part of your screen goes blank, make the textures for the background larger than the screen.
Here is how it can look like with 7 layers:

Props to LuminousDragonGames for the parallax images
https://opengameart.org/content/parallax-space-scene-seamlessly-scrolls-too