forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomMotionSystem.cs
More file actions
67 lines (60 loc) · 2.45 KB
/
Copy pathRandomMotionSystem.cs
File metadata and controls
67 lines (60 loc) · 2.45 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Physics.Systems;
using Unity.Transforms;
namespace Common.Scripts
{
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateBefore(typeof(PhysicsSystemGroup))]
public partial struct RandomMotionSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<RandomMotion>();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
if (!SystemAPI.TryGetSingleton<PhysicsStep>(out var stepComponent))
stepComponent = PhysicsStep.Default;
state.Dependency = new EntityRandomMotionJob
{
Random = new Random(),
DeltaTime = SystemAPI.Time.DeltaTime,
StepComponent = stepComponent
}.Schedule(state.Dependency);
}
[BurstCompile]
public partial struct EntityRandomMotionJob : IJobEntity
{
public Random Random;
public PhysicsStep StepComponent;
public float DeltaTime;
public void Execute(ref RandomMotion motion, ref PhysicsVelocity velocity, in LocalTransform transform, in PhysicsMass mass)
{
motion.CurrentTime += DeltaTime;
Random.InitState((uint)(motion.CurrentTime * 1000));
var currentOffset = transform.Position - motion.InitialPosition;
var desiredOffset = motion.DesiredPosition - motion.InitialPosition;
// If we are close enough to the destination pick a new destination
if (math.lengthsq(transform.Position - motion.DesiredPosition) < motion.Tolerance)
{
var min = new float3(-math.abs(motion.Range));
var max = new float3(math.abs(motion.Range));
desiredOffset = Random.NextFloat3(min, max);
motion.DesiredPosition = desiredOffset + motion.InitialPosition;
}
var offset = desiredOffset - currentOffset;
// Smoothly change the linear velocity
velocity.Linear = math.lerp(velocity.Linear, offset, motion.Speed);
if (mass.InverseMass != 0)
{
velocity.Linear -= StepComponent.Gravity * DeltaTime;
}
}
}
}
}