1
0
mirror of synced 2024-12-12 14:31:04 +01:00
WACVR/Assets/Script/PanelButton.cs

103 lines
2.9 KiB
C#
Raw Normal View History

2022-05-18 06:38:11 +02:00
using System;
using System.Runtime.InteropServices;
using UnityEngine;
using WindowsInput.Native;
[RequireComponent(typeof(AudioSource))]
public class PanelButton : MonoBehaviour
2022-05-18 06:38:11 +02:00
{
[DllImport("user32.dll")]
public static extern uint MapVirtualKey(uint uCode, uint uMapType);
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
public event Action ButtonPressed;
public event Action ButtonReleased;
2022-05-18 06:38:11 +02:00
public VirtualKeyCode key;
public VirtualKeyCode key2;
public bool isToggle;
public bool doesBeep;
public bool isOn;
private int _insideColliderCount = 0;
private Renderer cr;
2022-05-18 06:38:11 +02:00
public GameObject camera;
private AudioSource audioSrc;
2022-05-24 02:14:40 +02:00
private static AudioClip btnSound;
void Start()
{
btnSound = Resources.Load<AudioClip>("Audio/button press");
cr = GetComponent<Renderer>();
audioSrc = GetComponent<AudioSource>();
audioSrc.playOnAwake = false;
audioSrc.clip = btnSound;
if (isToggle)
{
// initialize toggle state
ButtonPress();
ButtonRelease();
}
}
2022-05-18 06:38:11 +02:00
private void OnTriggerEnter(Collider other)
{
_insideColliderCount += 1;
ButtonPress();
if (doesBeep)
audioSrc.Play();
}
private void OnTriggerExit(Collider other)
{
_insideColliderCount = Mathf.Clamp(_insideColliderCount - 1, 0, _insideColliderCount);
if (_insideColliderCount == 0)
{
ButtonRelease();
}
}
private void ButtonPress()
{
ButtonPressed?.Invoke();
if (isToggle)
{
if (!isOn)
{
cr.material.color = Color.green;
keybd_event(System.Convert.ToByte(key2), (byte)MapVirtualKey((uint)key2, 0), 2, UIntPtr.Zero);
keybd_event(System.Convert.ToByte(key), (byte)MapVirtualKey((uint)key, 0), 0, UIntPtr.Zero);
isOn = true;
}
else
{
cr.material.color = Color.red;
keybd_event(System.Convert.ToByte(key), (byte)MapVirtualKey((uint)key, 0), 2, UIntPtr.Zero);
keybd_event(System.Convert.ToByte(key2), (byte)MapVirtualKey((uint)key2, 0), 0, UIntPtr.Zero);
isOn = false;
}
}
else
{
cr.material.color = Color.white;
keybd_event(System.Convert.ToByte(key), (byte)MapVirtualKey((uint)key, 0), 0, UIntPtr.Zero);
}
2022-05-18 06:38:11 +02:00
}
private void ButtonRelease()
2022-05-18 06:38:11 +02:00
{
ButtonReleased?.Invoke();
keybd_event(System.Convert.ToByte(key), (byte)MapVirtualKey((uint)key, 0), 2, UIntPtr.Zero);
keybd_event(System.Convert.ToByte(key2), (byte)MapVirtualKey((uint)key2, 0), 2, UIntPtr.Zero);
if (!isToggle)
cr.material.color = Color.gray;
2022-05-18 06:38:11 +02:00
}
}