+3 votes

Basically it's a background which moves with your mouse.

I would like to know how can I make it so I can enhance my game.

asked Oct 3, 2019 in Engine by Lapiz (Quarstudz) (22 points)

1 Answer

+4 votes

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 ParallaxBackgroundand two ore more ParallaxLayer as child nodes and each ParallaxLayer needs a Sprite as child. Give the first Spritethe background texture, the second Spritethe 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:

answered Mar 31 by joschi (22 points)

Oh my God I can't thank you enough for this!!
I've been trying to achieve this effect since so long, but couldn't find anything on the internet as well. I'm not good at math programming so I couldn't do it myself...
You're a lifesaver!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.