Created
August 26, 2016 05:50
-
-
Save pharan/373bcd7132e5c488a674bda103288d23 to your computer and use it in GitHub Desktop.
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??
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; | |
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