Skip to content

Instantly share code, notes, and snippets.

@abdelfattahradwan
Created July 6, 2021 04:15
Show Gist options
  • Save abdelfattahradwan/d44112fb75810e651a75961127690494 to your computer and use it in GitHub Desktop.
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.
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