BITFALL/Assets/BITKit/Unity/Scripts/Sensor/AudioSensor.cs

72 lines
2.4 KiB
C#
Raw Normal View History

2024-04-16 04:39:26 +08:00
using System;
2023-06-08 14:09:50 +08:00
using System.Collections;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Pool;
using System.Linq;
2024-04-15 14:57:50 +08:00
2023-06-08 14:09:50 +08:00
namespace BITKit.Sensors
{
public interface IAudioObject
{
float GetVolume();
}
2024-04-15 14:57:50 +08:00
public class AudioSensor : MonoBehaviour,ISensor
2023-06-08 14:09:50 +08:00
{
2024-05-03 18:29:09 +08:00
2023-06-08 14:09:50 +08:00
[Header(Constant.Header.Settings)]
2024-04-16 04:39:26 +08:00
[SerializeField] private bool autoUpdate;
2024-04-15 14:57:50 +08:00
[SerializeField]private float radius;
private readonly CacheList<Transform> cache = new();
2024-04-19 00:40:34 +08:00
private readonly CacheList<AudioSensorService.AudioSensorData> data = new();
public AudioSensorService.AudioSensorData[] Noises => data.ValueArray;
2024-05-03 18:29:09 +08:00
private readonly HashSet<int> _addedSet = new();
2024-04-16 04:39:26 +08:00
private void OnEnable()
{
Id = GetInstanceID();
SensorQueue.Register(Id,this);
}
private void OnDisable()
{
SensorQueue.UnRegister(Id);
}
2024-05-03 18:29:09 +08:00
public async UniTask Execute(float delta)
2023-06-08 14:09:50 +08:00
{
2024-04-15 14:57:50 +08:00
var position = transform.position;
cache.Clear();
2024-04-19 00:40:34 +08:00
data.Clear();
2024-05-03 18:29:09 +08:00
_addedSet.Clear();
await UniTask.SwitchToTaskPool();
var value = AudioSensorService.QuadtreeRoot.Find(new Bounds(position, Vector3.one * radius)).ToArray();
for (var index = 0; index < value.Length; index++)
2023-06-08 14:09:50 +08:00
{
2024-05-03 18:29:09 +08:00
var x = value[index];
2024-04-19 00:40:34 +08:00
var distance = Vector3.Distance(position, x.Position);
if (distance > radius) continue;
2024-05-03 18:29:09 +08:00
if (Ignores.Contains(x.Id)) continue;
_addedSet.Add(index);
// if (x.Transform)
// cache.Add(x.Transform);
// data.Add(x);
2023-06-08 14:09:50 +08:00
}
2024-04-19 00:40:34 +08:00
2024-05-03 18:29:09 +08:00
await UniTask.SwitchToMainThread();
if (destroyCancellationToken.IsCancellationRequested) return;
foreach (var x in _addedSet)
{
if (value[x].Transform)
cache.Add(value[x].Transform);
data.Add(value[x]);
}
2023-06-08 14:09:50 +08:00
}
2024-05-03 18:29:09 +08:00
2024-04-19 00:40:34 +08:00
public HashSet<int> Ignores { get; } = new();
2024-04-15 14:57:50 +08:00
public int Id { get; set; }
public IEnumerable<Transform> Get() => cache.ValueArray;
public bool IsValid(Collider _collider) => false;
public float GetDistance() => radius;
2024-04-16 04:39:26 +08:00
public bool AutoUpdate=>autoUpdate;
2023-06-08 14:09:50 +08:00
}
}