Last active
September 7, 2024 04:05
-
-
Save jessielw/c075a338951c438e43c227bbb3b31724 to your computer and use it in GitHub Desktop.
Unity 2D Parallax Effect script with Cinemachine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using Cinemachine; | |
public class ParallaxEffect : MonoBehaviour | |
{ | |
public Camera cam; | |
public Transform subject; | |
Vector2 startPosition; | |
float startZ; | |
Vector2 travel => (Vector2)cam.transform.position - startPosition; | |
float distanceFromSubject => transform.position.z - subject.position.z; | |
float clippingPlane => (cam.transform.position.z + (distanceFromSubject > 0 ? cam.farClipPlane : cam.nearClipPlane)); | |
float parallaxFactor => Mathf.Abs(distanceFromSubject) / clippingPlane; | |
public void Start() | |
{ | |
startPosition = transform.position; | |
startZ = transform.position.z; | |
// Subscribe to the CameraUpdatedEvent | |
CinemachineCore.CameraUpdatedEvent.AddListener(OnCameraUpdated); | |
} | |
private void OnDestroy() | |
{ | |
CinemachineCore.CameraUpdatedEvent.RemoveListener(OnCameraUpdated); | |
} | |
// This will be called after the camera is positioned | |
void OnCameraUpdated(CinemachineBrain brain) | |
{ | |
// Update the parallax effect based on the camera position (only affecting the X position) | |
float newPosX = startPosition.x + travel.x * parallaxFactor; | |
// Keep the original Y position, so it doesn't move vertically | |
transform.position = new Vector3(newPosX, transform.position.y, startZ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment