XRoom_Unity/Assets/sparker.cs
2025-05-31 10:20:20 +03:30

58 lines
1.6 KiB
C#

using System.Globalization;
using Fusion;
using Fusion.Addons.ConnectionManagerAddon;
using UnityEngine;
using UnityEngine.XR;
public class Sparker : NetworkBehaviour
{
public Transform pos;
public GameObject sparkPrefab;
private GameObject spark;
private UnityEngine.XR.InputDevice rightController;
public BNG.Grabbable grabbable;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rightController = InputDevices.GetDeviceAtXRNode(XRNode.RightHand);
}
// Update is called once per frame
void Update()
{
if (IsHeld() && CanTriggerSpark())
{
// Only trigger if the player is the owner of the object
if (HasStateAuthority)
{
RPC_TriggerSpark();
}
}
}
private bool IsHeld()
{
return grabbable.BeingHeld;
}
private bool CanTriggerSpark()
{
return !spark&((rightController.TryGetFeatureValue(UnityEngine.XR.CommonUsages.trigger, out float isPressed) && isPressed > 0.5f) || Input.GetKey(KeyCode.Z));
}
// Method to trigger spark and play sounds (combined in one RPC)
[Rpc(RpcSources.StateAuthority, RpcTargets.All)]
private void RPC_TriggerSpark()
{
// Instantiate the spark object on all clients
spark = Instantiate(sparkPrefab, pos.position, pos.rotation);
Destroy(spark, 4f);
// Play both the spark and clap sounds across the network
ConnectionManager.instance.PlaySound("spark", 1f);
ConnectionManager.instance.PlaySound("clap", 1f);
}
}