MIF_E31230837/Assets/Script/LightDetector.cs

84 lines
2.2 KiB
C#

using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Deteksi kecerahan kamera secara real-time.
/// Tampilkan/sembunyikan button senter otomatis berdasarkan brightness.
/// </summary>
public class LightDetector : MonoBehaviour
{
[Header("UI")]
public GameObject flashlightButton; // drag button senter ke sini
[Header("Pengaturan")]
[Range(0f, 1f)]
public float threshold = 0.15f; // di bawah nilai ini = gelap, button muncul
public float checkInterval = 0.5f; // cek setiap berapa detik
private WebCamTexture webCamTexture;
private float timer = 0f;
void Start()
{
// Sembunyikan button saat awal
if (flashlightButton != null)
flashlightButton.SetActive(false);
// Gunakan kamera belakang
WebCamDevice[] devices = WebCamTexture.devices;
string backCamName = "";
foreach (var d in devices)
{
if (!d.isFrontFacing)
{
backCamName = d.name;
break;
}
}
webCamTexture = new WebCamTexture(backCamName, 64, 64, 15); // resolusi kecil = ringan
webCamTexture.Play();
}
void Update()
{
if (webCamTexture == null || !webCamTexture.isPlaying) return;
timer += Time.deltaTime;
if (timer < checkInterval) return;
timer = 0f;
float brightness = GetAverageBrightness();
bool isDark = brightness < threshold;
if (flashlightButton != null)
flashlightButton.SetActive(isDark);
}
float GetAverageBrightness()
{
Color32[] pixels = webCamTexture.GetPixels32();
if (pixels == null || pixels.Length == 0) return 1f;
float total = 0f;
int step = Mathf.Max(1, pixels.Length / 256); // sample sebagian pixel saja biar ringan
int count = 0;
for (int i = 0; i < pixels.Length; i += step)
{
Color32 c = pixels[i];
// luminance sederhana
total += (c.r * 0.299f + c.g * 0.587f + c.b * 0.114f) / 255f;
count++;
}
return count > 0 ? total / count : 1f;
}
void OnDestroy()
{
if (webCamTexture != null && webCamTexture.isPlaying)
webCamTexture.Stop();
}
}