Created
July 6, 2021 04:15
-
-
Save abdelfattahradwan/d44112fb75810e651a75961127690494 to your computer and use it in GitHub Desktop.
Prevents first person objects from clipping through objects in world without needing a separate camera.
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 sealed class NoClip : MonoBehaviour | |
{ | |
[SerializeField] private float radius; | |
[SerializeField] private float distance; | |
[SerializeField] private AnimationCurve offsetCurve; | |
[SerializeField] private LayerMask clippingLayerMask; | |
private Vector3 _originalLocalPosition; | |
private void Start() => _originalLocalPosition = transform.localPosition; | |
private void Update() | |
{ | |
if (Physics.SphereCast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0.0f)), radius, out var hit, distance, clippingLayerMask)) | |
{ | |
transform.localPosition = _originalLocalPosition + new Vector3(0.0f, 0.0f, offsetCurve.Evaluate(hit.distance / distance)); | |
} | |
else | |
{ | |
transform.localPosition = _originalLocalPosition; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment