forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWanderSystem.cs
More file actions
63 lines (56 loc) · 2.31 KB
/
Copy pathWanderSystem.cs
File metadata and controls
63 lines (56 loc) · 2.31 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
#if !UNITY_DISABLE_MANAGED_COMPONENTS
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using Animator = UnityEngine.Animator;
using Random = Unity.Mathematics.Random;
namespace Graphical.AnimationWithGameObjects
{
public partial struct WanderSystem : ISystem
{
int isMovingID;
public void OnCreate(ref SystemState state)
{
isMovingID = Animator.StringToHash("IsMoving");
state.RequireForUpdate<ExecuteAnimationWithGameObjects>();
}
public void OnUpdate(ref SystemState state)
{
var movement = SystemAPI.Time.DeltaTime * 3f;
var time = (float)SystemAPI.Time.ElapsedTime;
var random = Random.CreateFromIndex(state.GlobalSystemVersion);
var animatorQuery = SystemAPI.QueryBuilder().WithAll<WanderState, Animator>().Build();
var entities = animatorQuery.ToEntityArray(Allocator.Temp);
foreach (var entity in entities)
{
var wanderState = state.EntityManager.GetComponentData<WanderState>(entity);
var animator = state.EntityManager.GetComponentObject<Animator>(entity);
var timeLeft = wanderState.NextActionTime - time;
bool isMoving = timeLeft > wanderState.Period / 2f;
animator.SetBool(isMovingID, isMoving);
}
foreach (var (transform, wanderState) in
SystemAPI.Query<RefRW<LocalTransform>, RefRW<WanderState>>())
{
var timeLeft = wanderState.ValueRO.NextActionTime - time;
if (timeLeft < 0f)
{
wanderState.ValueRW.Period = random.NextFloat(2f, 5f);
wanderState.ValueRW.NextActionTime += wanderState.ValueRO.Period;
var angle = random.NextFloat(0f, math.PI * 2f);
transform.ValueRW.Rotation = quaternion.RotateY(angle);
}
else
{
bool isMoving = timeLeft > wanderState.ValueRO.Period / 2f;
if (isMoving)
{
transform.ValueRW.Position += transform.ValueRO.Forward() * movement;
}
}
}
}
}
}
#endif