How would I create a parallax background which moves according to the position of the mouse?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Amateur.game.dev.

How would I create a parallax background which moves according to the position of the mouse? If you could, please show some example script

:bust_in_silhouette: Reply From: Andrea

Well, if you have a camera the parallax background will follow the camera movement, in that case i think the simpler option is to create your own moving background.

If you do not have a camera, you can set up the parallax background and layers in the tree

O: SceneRoot

  • : ParallaxBackground
    • : ParallaxLayer1
      • O: Sprite1
    • : ParallaxLayer2 #set different scale if you want them to move at differen speed
      • O: Sprite2

Then you can control everything with

$ParallaxBackground.scroll_offset=get_global_mouse_position()
get_global_mouse_position() isn't declared in the current class

Do I have to create a variable for it?

Amateur.game.dev. | 2021-01-10 20:21

no, you are probably just calling get_global_mouse_position() from a node that does not support this method, likely something that does not inherits from a canvas item.
what node is this script attached to?

Andrea | 2021-01-10 21:43

ParallaxBackground

Amateur.game.dev. | 2021-01-11 20:15

yep, that’s it, parallaxBackground extend from CanvasLayer, and do not support the get mouse position methods (in short, it is not a node related to the viewport directly, it does not know the position of the mouse. it is like asking the AudioStreamer node to tell you the mouse position)

you should call it from a canvasItem node, like Node2D or Control.
EG:

O: Node2D <==PLACE SCRIPT HERE ($ParallaxBackground.scroll_offset=get_global_mouse_position())

  • : ParallaxBackground**<== or place it here** ( scroll=get_parent ().get_global_mouse_position() l
    • : ParallaxLayer1
      • O: Sprite1
    • : ParallaxLayer2 #set different scale if you want them to move at differen speed
      • O: Sprite2

Andrea | 2021-01-11 20:47

Do I need to add anything because it parallax doesn’t move? No errors this time though

Amateur.game.dev. | 2021-01-14 17:34

difficult to answer, paste the code to clarify

Andrea | 2021-01-17 11:18

extends Node2D

func _ready():
    ($ParallaxBackground.scroll_offset=get_global_mouse_position())

Amateur.game.dev. | 2021-01-17 21:38