quantum-space-buddies/QSB/OrbSync/OrbUserEvent.cs

74 lines
2.6 KiB
C#
Raw Normal View History

2020-09-29 20:34:46 +00:00
using OWML.Common;
using QSB.Events;
using QSB.Messaging;
2020-09-05 12:24:51 +00:00
using QSB.TransformSync;
2020-09-29 20:34:46 +00:00
using QSB.Utility;
using QSB.WorldSync;
2020-09-05 12:24:51 +00:00
using System.Linq;
using UnityEngine.Networking;
namespace QSB.OrbSync
{
public class OrbUserEvent : QSBEvent<WorldObjectMessage>
{
public override EventType Type => EventType.OrbUser;
2020-09-05 14:46:20 +00:00
public override void SetupListener() => GlobalMessenger<int>.AddListener(EventNames.QSBOrbUser, Handler);
2020-09-05 14:46:20 +00:00
public override void CloseListener() => GlobalMessenger<int>.RemoveListener(EventNames.QSBOrbUser, Handler);
private void Handler(int id) => SendEvent(CreateMessage(id));
private WorldObjectMessage CreateMessage(int id) => new WorldObjectMessage
{
AboutId = LocalPlayerId,
ObjectId = id
};
2020-09-05 12:24:51 +00:00
public override void OnServerReceive(WorldObjectMessage message)
{
2020-09-05 14:46:20 +00:00
var fromPlayer = NetworkServer.connections
.First(x => x.playerControllers[0].gameObject.GetComponent<PlayerTransformSync>().netId.Value == message.FromId);
2020-10-22 20:21:41 +00:00
if (WorldRegistry.OrbSyncList.Count == 0)
{
DebugLog.ToConsole($"Error - OrbSyncList is empty. (ID {message.ObjectId})", MessageType.Error);
return;
}
2020-09-06 08:07:31 +00:00
var orb = WorldRegistry.OrbSyncList
2020-09-05 14:46:20 +00:00
.First(x => x.AttachedOrb == WorldRegistry.OldOrbList[message.ObjectId]);
2020-09-29 20:34:46 +00:00
if (orb == null)
{
DebugLog.ToConsole($"Error - No orb found for user event. (ID {message.ObjectId})", MessageType.Error);
return;
}
2020-09-05 14:31:09 +00:00
var orbIdentity = orb.GetComponent<NetworkIdentity>();
2020-10-22 20:21:41 +00:00
if (orbIdentity == null)
{
DebugLog.ToConsole($"Error - Orb identity is null. (ID {message.ObjectId})", MessageType.Error);
return;
}
2020-09-06 08:07:31 +00:00
if (orbIdentity.clientAuthorityOwner != null)
{
orbIdentity.RemoveClientAuthority(orbIdentity.clientAuthorityOwner);
}
2020-09-05 12:24:51 +00:00
orbIdentity.AssignClientAuthority(fromPlayer);
2020-09-06 08:07:31 +00:00
orb.enabled = true;
}
public override void OnReceiveRemote(WorldObjectMessage message)
{
var orb = WorldRegistry.OrbSyncList
.First(x => x.AttachedOrb == WorldRegistry.OldOrbList[message.ObjectId]);
orb.enabled = true;
}
2020-09-05 12:24:51 +00:00
public override void OnReceiveLocal(WorldObjectMessage message)
{
if (NetworkServer.active)
{
OnServerReceive(message);
}
}
}
}