Advertisement
LeeMace

Parallax Controller

Feb 14th, 2023 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.16 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. //put this on the parent layer.
  6. /*Finds all of the gameObjects that have a ParallaxLayer.cs script, and moves them!*/
  7.  
  8. public class ParallaxController : MonoBehaviour
  9. {
  10.     public delegate void ParallaxCameraDelegate(float cameraPositionChangeX, float cameraPositionChangeY);
  11.     public ParallaxCameraDelegate onCameraMove;
  12.     private Vector2 oldCameraPosition;
  13.     List<ParallaxLayer> parallaxLayers = new List<ParallaxLayer>();
  14.  
  15.     void Start()
  16.     {
  17.         onCameraMove += MoveLayer;
  18.         FindLayers();
  19.         oldCameraPosition.x = Camera.main.transform.position.x;
  20.         oldCameraPosition.y = Camera.main.transform.position.y;
  21.     }
  22.  
  23.     private void FixedUpdate()
  24.     {
  25.         if (Camera.main.transform.position.x != oldCameraPosition.x || (Camera.main.transform.position.y) != oldCameraPosition.y)
  26.         {
  27.             if (onCameraMove != null)
  28.             {
  29.                 Vector2 cameraPositionChange;
  30.                 cameraPositionChange = new Vector2(oldCameraPosition.x - Camera.main.transform.position.x, oldCameraPosition.y - Camera.main.transform.position.y);
  31.                 onCameraMove(cameraPositionChange.x, cameraPositionChange.y);
  32.             }
  33.  
  34.             oldCameraPosition = new Vector2(Camera.main.transform.position.x, Camera.main.transform.position.y);
  35.         }
  36.     }
  37.  
  38.     //Finds all the objects that have a ParallaxLayer component, and adds them to the parallaxLayers list.
  39.     void FindLayers()
  40.     {
  41.         parallaxLayers.Clear();
  42.  
  43.         for (int i = 0; i < transform.childCount; i++)
  44.         {
  45.             ParallaxLayer layer = transform.GetChild(i).GetComponent<ParallaxLayer>();
  46.  
  47.             if (layer != null)
  48.             {
  49.                 parallaxLayers.Add(layer);
  50.             }
  51.         }
  52.     }
  53.  
  54.     //Move each layer based on each layers position. This is being used via the ParallaxLayer script
  55.     void MoveLayer(float positionChangeX, float positionChangeY)
  56.     {
  57.         foreach (ParallaxLayer layer in parallaxLayers)
  58.         {
  59.             layer.MoveLayer(positionChangeX, positionChangeY);
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement