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

76 lines
2.5 KiB
C#
Raw Normal View History

2024-04-20 17:29:39 +02:00
using System.Collections.Generic;
2024-04-20 01:52:41 +02:00
using UnityEngine;
public class HideWall : MonoBehaviour
{
[SerializeField] private GameObject target;
[SerializeField] private GameObject origin;
2024-04-20 16:52:39 +02:00
public GameObject prevObject;
2024-04-20 01:52:41 +02:00
public Material defaultMaterial; // Material when not hitting "Wall"
public Material hitMaterial; // Material when hitting "Wall"
2024-04-20 16:52:39 +02:00
public float sphereRadius;
2024-04-20 17:29:39 +02:00
float maxSphereRayDistance;
public Vector3 maxSphereRayDistanceOffset;
private List<GameObject> prevHitObjects = new List<GameObject>();
2024-04-20 16:52:39 +02:00
private void Start()
{
2024-04-20 17:29:39 +02:00
maxSphereRayDistance = Vector3.Distance(origin.transform.position, target.transform.position) - (sphereRadius * 2 + 1);
2024-04-20 16:52:39 +02:00
}
2024-04-20 01:52:41 +02:00
void Update()
{
2024-04-20 17:29:39 +02:00
Vector3 direction = ((target.transform.position + maxSphereRayDistanceOffset) - origin.transform.position).normalized;
RaycastHit[] hits = Physics.SphereCastAll(origin.transform.position, sphereRadius, direction, maxSphereRayDistance);
2024-04-20 16:52:39 +02:00
2024-04-20 17:29:39 +02:00
List<GameObject> hitObjectsThisFrame = new List<GameObject>();
2024-04-20 01:52:41 +02:00
2024-04-20 17:29:39 +02:00
// Change material of currently hit objects
for (int i = 0; i < hits.Length; i++)
2024-04-20 01:52:41 +02:00
{
2024-04-20 17:29:39 +02:00
if (hits[i].collider.CompareTag("Wall"))
2024-04-20 01:52:41 +02:00
{
2024-04-20 17:29:39 +02:00
var hitGameObject = hits[i].collider.gameObject;
hitObjectsThisFrame.Add(hitGameObject);
// Change material only if this object wasn't hit last frame
if (!prevHitObjects.Contains(hitGameObject))
{
Renderer renderer = hits[i].collider.GetComponent<Renderer>();
if (renderer != null)
2024-04-20 15:33:12 +02:00
{
2024-04-20 17:29:39 +02:00
renderer.material = hitMaterial;
2024-04-20 15:33:12 +02:00
}
2024-04-20 17:29:39 +02:00
}
}
}
2024-04-20 15:33:12 +02:00
2024-04-20 17:29:39 +02:00
// Restore the material of objects that are not hit this frame but were hit in the previous frame
for (int i = 0; i < prevHitObjects.Count; i++)
{
if (!hitObjectsThisFrame.Contains(prevHitObjects[i]))
{
Renderer renderer = prevHitObjects[i].GetComponent<Renderer>();
if (renderer != null)
{
renderer.material = defaultMaterial;
}
2024-04-20 01:52:41 +02:00
}
}
2024-04-20 17:29:39 +02:00
// Update the list of previously hit objects
prevHitObjects = hitObjectsThisFrame;
2024-04-20 01:52:41 +02:00
}
2024-04-20 17:29:39 +02:00
2024-04-20 01:52:41 +02:00
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
2024-04-20 16:52:39 +02:00
Gizmos.DrawWireSphere(origin.transform.position, sphereRadius);
2024-04-20 01:52:41 +02:00
}
}