3DTD/Assets/Scripts/Camera/HideWall.cs

88 lines
2.7 KiB
C#

using System.Collections.Generic;
using UnityEngine;
public class HideWall : MonoBehaviour
{
public static HideWall instance;
[SerializeField] private GameObject originalTarget;
public GameObject target;
[SerializeField] private GameObject origin;
[Range(1f, 10f)] public float hideFadeSpeed;
[Range(1f, 10f)] public float showFadeSpeed;
public float sphereRadius;
float maxSphereRayDistance;
private List<GameObject> prevHitObjects = new List<GameObject>();
private void Start()
{
if (instance == null)
instance = this;
}
void Update()
{
if (target == null)
target = originalTarget;
maxSphereRayDistance = Vector3.Distance(origin.transform.position, target.transform.position) - (sphereRadius);
Vector3 direction = (target.transform.position - origin.transform.position).normalized;
RaycastHit[] hits = Physics.SphereCastAll(origin.transform.position, sphereRadius, direction, maxSphereRayDistance);
List<GameObject> hitObjectsThisFrame = new List<GameObject>();
for (int i = 0; i < hits.Length; i++)
{
//print(hits[i].collider.gameObject.name);
if (hits[i].collider != null)
{
var hitGameObject = hits[i].collider.gameObject;
hitObjectsThisFrame.Add(hitGameObject);
var wallOpacity = hitGameObject.GetComponent<WallOpacity>();
if (wallOpacity != null && !prevHitObjects.Contains(hitGameObject))
{
wallOpacity.HideWall(hideFadeSpeed);
}
}
}
foreach (var prevHitObject in prevHitObjects)
{
if (prevHitObject == null) break;
if (!hitObjectsThisFrame.Contains(prevHitObject))
{
var wallOpacity = prevHitObject.GetComponent<WallOpacity>();
if (wallOpacity != null)
{
wallOpacity.ShowWall(showFadeSpeed);
}
}
}
prevHitObjects = hitObjectsThisFrame;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(origin.transform.position, sphereRadius);
if(target != null && origin != null)
maxSphereRayDistance = Vector3.Distance(origin.transform.position, target.transform.position) - (sphereRadius);
if(origin != null && target != null)
{
Vector3 direction = (target.transform.position - origin.transform.position).normalized;
Gizmos.DrawRay(origin.transform.position, direction * maxSphereRayDistance);
}
}
}