Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simplified (derived) formula for faking the parallax of an object given a camera position, in the form of a Unity component. This may not work for VR??
using UnityEngine;
public class ParallaxFaker2D : MonoBehaviour {
// The Transform of the camera to fake the parallax for.
public Transform cameraTransform;
// The world position to mimick the parallax of.
public Vector3 fakePosition;
// The Transform's target (actual) distance from the camera.
// This will be scaled according to the parallax factor so moving the camera along the Z will also result in a proportionate Z movement according to the fake position.
public float targetCameraDistance;
// An arbitrary value. Set this according to what you think your typical camera.transform.position.z will be.
const float BaseCameraZ = -10f; // Setting this to 0 will collapse the transformation.
void LateUpdate () {
Vector3 cameraPosition = cameraTransform.position;
float fakePositionBaseDistance = (fakePosition.z - BaseCameraZ);
float parallaxFactor = fakePositionBaseDistance == 0 ? 0 : (targetCameraDistance / fakePositionBaseDistance);
Vector3 parallaxedCameraOffset = (fakePosition - cameraPosition) * parallaxFactor;
transform.localPosition = cameraPosition + parallaxedCameraOffset; // Apply worldPosition as localPosition if you know it doesn't inherit any Transform.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment