NetworkConnection.observing sorted by distance to NetworkConnection's main player

This commit is contained in:
vis2k 2021-05-14 17:55:19 +08:00
parent 03867e027d
commit b0c2b34f3a
3 changed files with 39 additions and 1 deletions

View File

@ -10,8 +10,10 @@ public abstract class NetworkConnection
public const int LocalConnectionId = 0;
// NetworkIdentities that this connection can see
// sorted by distance to the main player object,
// which is necessary for priority based WorldState sync
// TODO move to server's NetworkConnectionToClient?
internal readonly HashSet<NetworkIdentity> observing = new HashSet<NetworkIdentity>();
internal readonly SortedSet<NetworkIdentity> observing;
// TODO this is NetworkServer.handlers on server and NetworkClient.handlers on client.
// maybe use them directly. avoid extra state.
@ -52,6 +54,9 @@ public abstract class NetworkConnection
internal NetworkConnection()
{
// initialize 'observing' with the custom comparer
observing = new SortedSet<NetworkIdentity>(new ObservingComparer(this));
// set lastTime to current time when creating connection to make
// sure it isn't instantly kicked for inactivity
lastMessageTime = Time.time;

View File

@ -0,0 +1,30 @@
using System.Collections.Generic;
using UnityEngine;
namespace Mirror
{
// Comparer for our observing sorted set
internal class ObservingComparer : IComparer<NetworkIdentity>
{
// need to know the main player object's position
NetworkConnection owner;
internal ObservingComparer(NetworkConnection owner)
{
this.owner = owner;
}
public int Compare(NetworkIdentity a, NetworkIdentity b)
{
// does owner connection have a player?
if (owner.identity != null)
{
// calculate both identity's distances to the player
Vector3 ownerPosition = owner.identity.transform.position;
float distanceA = Vector3.Distance(ownerPosition, a.transform.position);
float distanceB = Vector3.Distance(ownerPosition, b.transform.position);
return Comparer<float>.Default.Compare(distanceA, distanceB);
}
return 0;
}
}
}

View File

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9e677be00d394c8a8f6a74c26dfe2502
timeCreated: 1620986031