Skip to content

Commit 23766a3

Browse files
optimized sorting
1 parent cd57e26 commit 23766a3

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

Assets/BossRoom/Scripts/Client/Game/Character/ClientInputSender.cs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ struct ActionRequest
102102

103103
const float k_MaxNavMeshDistance = 1f;
104104

105+
RaycastHitComparer m_RaycastHitComparer;
106+
105107
public override void OnNetworkSpawn()
106108
{
107109
if (!IsClient || !IsOwner)
@@ -113,6 +115,8 @@ public override void OnNetworkSpawn()
113115

114116
m_GroundLayerMask = LayerMask.GetMask(new[] { "Ground" });
115117
m_ActionLayerMask = LayerMask.GetMask(new[] { "PCs", "NPCs", "Ground" });
118+
119+
m_RaycastHitComparer = new RaycastHitComparer();
116120
}
117121

118122
void Awake()
@@ -177,16 +181,17 @@ void FixedUpdate()
177181
k_CachedHit[i] = default;
178182
}
179183

180-
if (Physics.RaycastNonAlloc(ray, k_CachedHit, k_MouseInputRaycastDistance, m_GroundLayerMask) > 0)
184+
var groundHits = Physics.RaycastNonAlloc(ray, k_CachedHit, k_MouseInputRaycastDistance, m_GroundLayerMask);
185+
if (groundHits > 0)
181186
{
182-
// sort hits by distance
183-
Array.Sort(k_CachedHit, (hit1, hit2) => hit1.distance.CompareTo(hit2.distance));
184-
185-
// find shortest-distance RaycastHit
186-
var closestHit = Array.Find(k_CachedHit, (sortedHit) => sortedHit.collider != null);
187+
if (groundHits > 1)
188+
{
189+
// sort hits by distance
190+
Array.Sort(k_CachedHit, 0, groundHits, m_RaycastHitComparer);
191+
}
187192

188193
// verify point is indeed on navmesh surface
189-
if (NavMesh.SamplePosition(closestHit.point, out var hit, k_MaxNavMeshDistance, NavMesh.AllAreas))
194+
if (NavMesh.SamplePosition(k_CachedHit[0].point, out var hit, k_MaxNavMeshDistance, NavMesh.AllAreas))
190195
{
191196
m_NetworkCharacter.SendCharacterInputServerRpc(hit.position);
192197

Assets/BossRoom/Scripts/Shared/Game/Action/ActionUtils.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Collections.Generic;
12
using Unity.Netcode;
23
using UnityEngine;
34

@@ -217,4 +218,15 @@ public static class ActionConclusion
217218
public const bool Stop = false;
218219
public const bool Continue = true;
219220
}
221+
222+
/// <summary>
223+
/// Utility comparer to sort through RaycastHits by distance.
224+
/// </summary>
225+
public class RaycastHitComparer : IComparer<RaycastHit>
226+
{
227+
public int Compare(RaycastHit x, RaycastHit y)
228+
{
229+
return x.distance.CompareTo(y.distance);
230+
}
231+
}
220232
}

0 commit comments

Comments
 (0)