forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindNearestJob.cs
More file actions
52 lines (46 loc) · 1.9 KB
/
Copy pathFindNearestJob.cs
File metadata and controls
52 lines (46 loc) · 1.9 KB
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
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
// We'll use Unity.Mathematics.float3 instead of Vector3,
// and we'll use Unity.Mathematics.math.distancesq instead of Vector3.sqrMagnitude.
using Unity.Mathematics;
// Include the BurstCompile attribute to Burst compile the job.
[BurstCompile]
public struct FindNearestJob : IJob
{
// All of the data which a job will access should
// be included in its fields. In this case, the job needs
// three arrays of float3.
// Array and collection fields that are only read in
// the job should be marked with the ReadOnly attribute.
// Although not strictly necessary in this case, marking data
// as ReadOnly may allow the job scheduler to safely run
// more jobs concurrently with each other.
// (See the "Intro to jobs" for more detail.)
[ReadOnly] public NativeArray<float3> TargetPositions;
[ReadOnly] public NativeArray<float3> SeekerPositions;
// For SeekerPositions[i], we will assign the nearest
// target position to NearestTargetPositions[i].
public NativeArray<float3> NearestTargetPositions;
// 'Execute' is the only method of the IJob interface.
// When a worker thread executes the job, it calls this method.
public void Execute()
{
// Compute the square distance from each seeker to every target.
for (int i = 0; i < SeekerPositions.Length; i++)
{
float3 seekerPos = SeekerPositions[i];
float nearestDistSq = float.MaxValue;
for (int j = 0; j < TargetPositions.Length; j++)
{
float3 targetPos = TargetPositions[j];
float distSq = math.distancesq(seekerPos, targetPos);
if (distSq < nearestDistSq)
{
nearestDistSq = distSq;
NearestTargetPositions[i] = targetPos;
}
}
}
}
}