Files
jelito/Assets/jelycho/Code/ButtonActor.cs
2025-07-17 00:49:04 +02:00

90 lines
2.6 KiB
C#

using System;
using Cysharp.Threading.Tasks;
using RebootKit.Engine.Simulation;
using UnityEngine;
using UnityEngine.Events;
using Logger = RebootKit.Engine.Foundation.Logger;
namespace RebootReality.jelycho {
public class ButtonActor : Actor, IInteractable {
static readonly Logger s_Logger = new Logger(nameof(ButtonActor));
[SerializeField] Outline m_Outline;
[SerializeField] Transform m_Graphics;
[SerializeField] float m_CooldownDuration = 0.5f;
DateTime m_LastPressTime;
public UnityEvent pressed = new UnityEvent();
//
// @MARK: Unity callbacks
//
void Awake() {
SetHighlight(false);
m_LastPressTime = DateTime.MinValue;
}
//
// @MARK: Actor
//
protected override IActorData CreateActorData() {
return new NoActorData();
}
protected override void OnActorCommandServer(ActorCommand actorCommand) {
if (actorCommand.CommandID == (ushort) ButtonActorCommands.Press) {
if (DateTime.UtcNow - m_LastPressTime < TimeSpan.FromSeconds(m_CooldownDuration)) {
return;
}
m_LastPressTime = DateTime.UtcNow;
SendActorEvent((ushort) ButtonActorEvents.Pressed);
pressed?.Invoke();
}
}
protected override void OnActorEventClient(ActorEvent actorEvent) {
if (actorEvent.EventID == (ushort) ButtonActorEvents.Pressed) {
PlayPressAnimation();
}
}
void PlayPressAnimation() {
PressAsync().Forget();
}
async UniTask PressAsync() {
m_Graphics.localScale = new Vector3(1, 0.1f, 1);
await UniTask.Delay(TimeSpan.FromSeconds(m_CooldownDuration), cancellationToken: destroyCancellationToken);
m_Graphics.localScale = new Vector3(1, 1, 1);
}
//
// @MARK: IInteractable
//
public void SetHighlight(bool highlight) {
if (m_Outline == null) {
Debug.LogError("ButtonActor does not have an Outline component.");
return;
}
m_Outline.enabled = highlight;
}
public void Interact() {
SendActorCommand((ushort) ButtonActorCommands.Press);
}
}
public enum ButtonActorCommands : ushort {
None = 0x0000,
Press = 0x0001,
}
public enum ButtonActorEvents : ushort {
None = 0x0000,
Pressed = 0x0001,
}
}