Skip to content

Instantly share code, notes, and snippets.

@pharan
Created August 26, 2016 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pharan/c9ba09ea346a4db6be7e0853a4b72037 to your computer and use it in GitHub Desktop.
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.
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