Last active
August 30, 2022 22:00
-
-
Save winstxnhdw/1f2c2d96a2ec8fd7496049c39d6a625a to your computer and use it in GitHub Desktop.
Fades a canvas in when the camera is near; fades a canvas out when the camera is too far. No shaders required. Attach script to Canvas with a CanvasGroup component.
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 System; | |
using UnityEngine; | |
// Fades a canvas in when the camera is near. | |
// Fades a canvas out when the camera is too far. | |
[RequireComponent(typeof(CanvasGroup))] | |
public class SoftClipping : MonoBehaviour { | |
const float maxAlpha = 1.0f; | |
const float maxViewDistance = 4.0f; | |
const float fadeInDistance = 2.0f; | |
CanvasGroup canvasGroup; | |
void Awake() { | |
if (fadeInDistance >= maxViewDistance) throw new Exception("fadeInDistance must be less than maxViewDistance"); | |
CameraMovementListener.onCameraMove += this.UpdateCanvasAlpha; | |
this.canvasGroup = GetComponent<CanvasGroup>(); | |
this.UpdateCanvasAlpha(); | |
} | |
void UpdateCanvasAlpha() { | |
// https://www.desmos.com/calculator/odnqb9ebmt | |
float CameraNearClipPlane = Camera.main.transform.position.z + Camera.main.nearClipPlane; | |
this.canvasGroup.alpha = maxAlpha * (CameraNearClipPlane - transform.position.z + maxViewDistance) / fadeInDistance; | |
} | |
void OnDestroy() { | |
CameraMovementListener.onCameraMove -= this.UpdateCanvasAlpha; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment