using System.Collections; using System.Collections.Generic; using UnityEditor.Rendering; using UnityEngine; using UnityEngine.UIElements; public class DepthTester : MonoBehaviour { public int FrameRes = 256; public float Offset = 0.02f; private RenderTexture texture; public Texture2D texture2D; private Camera camera; private float farPlane; private float nearPlane; // Start is called before the first frame update void Start() { camera = GetComponent(); farPlane = camera.farClipPlane; nearPlane = camera.nearClipPlane; texture = BlendShaderController.CreateTextures(1, FrameRes, FrameRes, false)[0]; camera.targetTexture = texture; texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBAFloat, false); } private void OnDisable() { if (texture != null) { Destroy(texture); } if (texture2D != null) { Destroy(texture2D); } } private void Update() { Vector3 depthPos = transform.position + transform.right * Offset; RenderTexture.active = texture; texture2D.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0); texture2D.Apply(); Color pixel = texture2D.GetPixel(texture.width / 2, texture2D.height / 2); float depth = pixel.r; float depthDist = depth * farPlane; Debug.DrawLine(depthPos, depthPos + transform.forward * depthDist, Color.green); Vector3 raycastPos = transform.position - transform.right * Offset; float rayDistance = 0; if(Physics.Raycast(transform.position, transform.forward, out var hit, 100)) { rayDistance = hit.distance; Debug.DrawLine(raycastPos, raycastPos + transform.forward * rayDistance, Color.red); } } }