Skip to content

Instantly share code, notes, and snippets.

@rsaenzi
Last active April 12, 2021 04:17
Show Gist options
  • Save rsaenzi/9d4e5fdd0bb105f6df11f1e60a776e98 to your computer and use it in GitHub Desktop.
Save rsaenzi/9d4e5fdd0bb105f6df11f1e60a776e98 to your computer and use it in GitHub Desktop.
Script for Unity to implement Parallax effect for backgrounds on 2D games
//
// Parallax.cs
//
// Created by Rigoberto Sáenz Imbacuán (https://linkedin.com/in/rsaenzi/)
// Copyright © 2021. All rights reserved.
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class Parallax : MonoBehaviour {
[Tooltip("Horizontal motion speed in meters/seconds")]
public float motionSpeed;
[Tooltip("Width of the camera's frustrum in meters")]
public float screenSize;
void Update() {
// Moves the background to left
transform.Translate(Vector3.left * motionSpeed * Time.deltaTime, Space.Self);
// If background reaches the left limit, we move it right twice the size of it
if (transform.position.x <= -screenSize) {
transform.Translate(screenSize * 2, 0, 0, Space.World);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment