Wednesday, April 18, 2018

18. Parallax

We have 3 scenes: red.tscn, green.tscn, blue.tscn that contain a sprite of 16 by 16 with the color indicated.


In the main scene with root node of Node2D, we have a ParallaxBackground node with 3 ParallaxLayer childs.


This script is attached to the Node2D.



extends Node2D

onready var layer1 = get_node("parallax/layer1")
onready var layer2 = get_node("parallax/layer2")
onready var layer3 = get_node("parallax/layer3")

func _ready():
    var red_scene = load("res://red.tscn")
    var green_scene = load("res://green.tscn")
    var blue_scene = load("res://blue.tscn")
    var red
    var green
    var blue
    for i in range(10):
        red = red_scene.instance()
        red.position = Vector2(20 * i + 10, 10)
        green = green_scene.instance()
        green.position = Vector2(20 * i + 10, 30)
        blue = blue_scene.instance()
        blue.position = Vector2(20 * i + 10, 50)
    layer1.add_child(red)
    layer2.add_child(green)
    layer3.add_child(blue)


func _process(delta):
    layer1.motion_offset.x += 1
    layer2.motion_offset.x += 1.5
    layer3.motion_offset.x += 2


This is the output showing the layers moving at different speeds.


No comments:

Post a Comment