-
-
Notifications
You must be signed in to change notification settings - Fork 742
/
DistanceInterestManagement.cs
74 lines (66 loc) · 2.98 KB
/
DistanceInterestManagement.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// straight forward Vector3.Distance based interest management.
using System.Collections.Generic;
using UnityEngine;
namespace Mirror
{
public class DistanceInterestManagement : InterestManagement
{
[Tooltip("The maximum range that objects will be visible at. Add DistanceInterestManagementCustomRange onto NetworkIdentities for custom ranges.")]
public int visRange = 10;
[Tooltip("Rebuild all every 'rebuildInterval' seconds.")]
public float rebuildInterval = 1;
double lastRebuildTime;
// helper function to get vis range for a given object, or default.
int GetVisRange(NetworkIdentity identity)
{
DistanceInterestManagementCustomRange custom = identity.GetComponent<DistanceInterestManagementCustomRange>();
return custom != null ? custom.visRange : visRange;
}
[ServerCallback]
public override void Reset()
{
lastRebuildTime = 0D;
}
public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnection newObserver)
{
int range = GetVisRange(identity);
return Vector3.Distance(identity.transform.position, newObserver.identity.transform.position) < range;
}
public override void OnRebuildObservers(NetworkIdentity identity, HashSet<NetworkConnection> newObservers, bool initialize)
{
// cache range and .transform because both call GetComponent.
int range = GetVisRange(identity);
Vector3 position = identity.transform.position;
// brute force distance check
// -> only player connections can be observers, so it's enough if we
// go through all connections instead of all spawned identities.
// -> compared to UNET's sphere cast checking, this one is orders of
// magnitude faster. if we have 10k monsters and run a sphere
// cast 10k times, we will see a noticeable lag even with physics
// layers. but checking to every connection is fast.
foreach (NetworkConnectionToClient conn in NetworkServer.connections.Values)
{
// authenticated and joined world with a player?
if (conn != null && conn.isAuthenticated && conn.identity != null)
{
// check distance
if (Vector3.Distance(conn.identity.transform.position, position) < range)
{
newObservers.Add(conn);
}
}
}
}
// internal so we can update from tests
[ServerCallback]
internal void Update()
{
// rebuild all spawned NetworkIdentity's observers every interval
if (NetworkTime.localTime >= lastRebuildTime + rebuildInterval)
{
RebuildAll();
lastRebuildTime = NetworkTime.localTime;
}
}
}
}