Created
August 26, 2016 06:01
-
-
Save pharan/c9ba09ea346a4db6be7e0853a4b72037 to your computer and use it in GitHub Desktop.
Formula for scaling an object according to how far it moves from an original point and viewpoint, in order to maintain its perceived size. In the form of a Unity MonoBehaviour. This is to achieve VR-friendly parallax for 2D games.
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; | |
/// <summary> | |
/// This script will push an object back to a target Z position and maintain its size to a given editor camera distance. This is to achieve parallax that is compatible with VR.</summary> | |
public class DistanceApplier : MonoBehaviour { | |
public float targetZ = 20; | |
// The applied scale will try to maintain the scale of the object assuming the original scale was defined when viewed with the camera at this z position. | |
const float BaseCameraZ = -10; | |
void Awake () { | |
Vector3 originalPosition = transform.localPosition; | |
float originalDistance = BaseCameraZ - originalPosition.z; | |
float newDistance = BaseCameraZ - targetZ; | |
float uniformScale = originalDistance == 0 ? 0 : newDistance / originalDistance; | |
transform.localPosition = new Vector3( | |
originalPosition.x, | |
originalPosition.y, | |
targetZ | |
); | |
transform.localScale *= uniformScale; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment