forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdateHealthBarSystem.cs
More file actions
75 lines (67 loc) · 3.08 KB
/
Copy pathUpdateHealthBarSystem.cs
File metadata and controls
75 lines (67 loc) · 3.08 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
68
69
70
71
72
73
74
75
using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
using Unity.Transforms;
using UnityEngine;
using UnityEngine.UI;
namespace Samples.HelloNetcode
{
#if !UNITY_DISABLE_MANAGED_COMPONENTS
/// <summary>
/// Update position and rotation of the health bar above players. This will make sure the health bar follow the character
/// character and is always facing the main camera.
/// </summary>
[WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation)]
[UpdateInGroup(typeof(PresentationSystemGroup))]
[RequireMatchingQueriesForUpdate]
public partial struct UpdateHealthBarSystem : ISystem
{
public void OnUpdate(ref SystemState state)
{
if (Camera.main == null)
{
state.Enabled = false;
return;
}
var mainCamera = Camera.main;
foreach (var (ui, health, act, owner, ltw, entity) in SystemAPI.Query<HealthUI, RefRO<Health>, RefRO<AutoCommandTarget>, RefRO<GhostOwner>, RefRO<LocalToWorld>>().WithEntityAccess())
{
if (state.EntityManager.IsComponentEnabled<GhostOwnerIsLocal>(entity))
{
// Move the UI on top of the local player, so that you can see.
var targetHealthBarPos = ltw.ValueRO.Position;
targetHealthBarPos.y += ui.PlayerHeightOffset;
var n = mainCamera.transform.position - ui.HealthBar.position;
targetHealthBarPos += (float3)(n.normalized * ui.PlayerTowardCameraOffset);
ui.HealthBar.SetPositionAndRotation(targetHealthBarPos, Quaternion.LookRotation(n));
}
else
{
// Move the UI above the players head.
var targetHealthBarPos = ltw.ValueRO.Position;
targetHealthBarPos.y += ui.OpponentHeightOffset;
var n = mainCamera.transform.position - ui.HealthBar.position;
ui.HealthBar.SetPositionAndRotation(targetHealthBarPos, Quaternion.LookRotation(n));
}
var hpNormalized = math.saturate((float)health.ValueRO.CurrentHitPoints / health.ValueRO.MaximumHitPoints);
var playerColor = NetworkIdDebugColorUtility.GetColor(owner.ValueRO.NetworkId);
// Killed by server:
if (act.ValueRO.Enabled)
{
// Set to players color:
ui.HealthSlider.color = playerColor;
}
else
{
// Set to 0 regardless of prediction, and change the background to an authoritative dead.
// Note that we only do this once AutoCommandTarget is set. Why? We're waiting for server confirmation.
hpNormalized = 0;
playerColor.a = 0.3f;
ui.HealthSlider.transform.parent.GetComponent<Image>().color = playerColor;
}
ui.HealthSlider.fillAmount = hpNormalized;
}
}
}
#endif
}