Targeting
Target locking
Crosshairs
Improved HUD schematic feedback
Equipment Heat Damage
Equipment Disabling
This commit is contained in:
Reinier Vens 2021-01-10 03:59:47 +00:00
commit fddd485262
100 changed files with 10091 additions and 7885 deletions

View file

@ -20,6 +20,10 @@ using float2 = Unity.Mathematics.float2;
public class ActionGameManager : MonoBehaviour
{
public PlaceUIElementWorldspace ViewDot;
public PlaceUIElementWorldspace TargetIndicator;
public Prototype LockIndicator;
public PlaceUIElementWorldspace[] Crosshairs;
public EventLog EventLog;
public GameSettings Settings;
public SectorRenderer SectorRenderer;
@ -48,6 +52,8 @@ public class ActionGameManager : MonoBehaviour
// private ShipInput _shipInput;
private float2 _shipYawPitch;
private float3 _viewDirection;
private (HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)[] ArticulationGroups;
private (TargetLock targetLock, PlaceUIElementWorldspace indicator, Rotate spin)[] LockingIndicators;
public List<Ship> PlayerShips { get; } = new List<Ship>();
public DatabaseCache ItemData { get; private set; }
@ -163,6 +169,38 @@ public class ActionGameManager : MonoBehaviour
else Undock();
};
_input.Player.TargetReticle.performed += context =>
{
var underReticle = Zone.Entities.MaxBy(x => dot(normalize(x.Position - _currentShip.Position), _currentShip.LookDirection));
_currentShip.Target.Value = _currentShip.Target.Value == underReticle ? null : underReticle;
TargetIndicator.gameObject.SetActive(_currentShip.Target.Value != null);
};
_input.Player.TargetNearest.performed += context =>
{
_currentShip.Target.Value = Zone.Entities.MaxBy(x => length(x.Position - _currentShip.Position));
};
_input.Player.TargetNext.performed += context =>
{
var targets = Zone.Entities.OrderBy(x => length(x.Position - _currentShip.Position)).ToArray();
if(_currentShip.Target.Value != null)
{
var currentTargetIndex = Array.IndexOf(targets, _currentShip.Target.Value);
_currentShip.Target.Value = targets[(currentTargetIndex + 1) % targets.Length];
}
};
_input.Player.TargetPrevious.performed += context =>
{
var targets = Zone.Entities.OrderBy(x => length(x.Position - _currentShip.Position)).ToArray();
if (_currentShip.Target.Value != null)
{
var currentTargetIndex = Array.IndexOf(targets, _currentShip.Target.Value);
_currentShip.Target.Value = targets[(currentTargetIndex + targets.Length - 1) % targets.Length];
}
};
#region Trigger Groups
_input.Player.PreviousWeaponGroup.performed += context =>
@ -452,6 +490,10 @@ public class ActionGameManager : MonoBehaviour
ship.TryEquip(ItemManager.CreateInstance(autocannonData, .5f, 1) as EquippableItem);
ship.TryEquip(ItemManager.CreateInstance(autocannonData, .5f, 1) as EquippableItem);
var lrmmData = ItemData.GetAll<GearData>().First(x => x.Name == "LRMM72");
ship.TryEquip(ItemManager.CreateInstance(lrmmData, .5f, 1) as EquippableItem);
ship.TryEquip(ItemManager.CreateInstance(lrmmData, .5f, 1) as EquippableItem);
var cargoData = ItemData.GetAll<CargoBayData>().First(x => x.Name == "Cargo Bay 4x4");
ship.TryEquip(ItemManager.CreateInstance(cargoData, .5f, 1) as EquippableItem);
@ -496,6 +538,8 @@ public class ActionGameManager : MonoBehaviour
Cursor.lockState = CursorLockMode.None;
_input.Player.Disable();
GameplayUI.SetActive(false);
if(LockingIndicators!=null) foreach(var (_, indicator, _) in LockingIndicators)
indicator.GetComponent<Prototype>().ReturnToPool();
}
}
}
@ -506,16 +550,19 @@ public class ActionGameManager : MonoBehaviour
if (_currentShip.Parent == null) return;
if (_currentShip.GetBehavior<Cockpit>() == null)
{
ConfirmationDialog.Clear();
ConfirmationDialog.Title.text = "Can't undock. Missing cockpit component!";
ConfirmationDialog.Show();
}
else if (_currentShip.GetBehavior<Thruster>() == null)
{
ConfirmationDialog.Clear();
ConfirmationDialog.Title.text = "Can't undock. Missing thruster component!";
ConfirmationDialog.Show();
}
else if (_currentShip.GetBehavior<Reactor>() == null)
{
ConfirmationDialog.Clear();
ConfirmationDialog.Title.text = "Can't undock. Missing reactor component!";
ConfirmationDialog.Show();
}
@ -528,10 +575,35 @@ public class ActionGameManager : MonoBehaviour
FollowCamera.enabled = true;
FollowCamera.LookAt = SectorRenderer.EntityInstances[_currentShip].LookAtPoint;
FollowCamera.Follow = SectorRenderer.EntityInstances[_currentShip].Transform;
ArticulationGroups = _currentShip.Equipment
.Where(item => item.Behaviors.Any(x => x.Data is WeaponData && !(x.Data is LauncherData)))
.GroupBy(item => SectorRenderer.EntityInstances[_currentShip]
.GetBarrel(_currentShip.Hardpoints[item.Position.x, item.Position.y])
.GetComponentInParent<ArticulationPoint>()?.Group ?? -1)
.Select((group, index) => {
return (
group.Select(item => _currentShip.Hardpoints[item.Position.x, item.Position.y]).ToArray(),
group.Select(item => SectorRenderer.EntityInstances[_currentShip].GetBarrel(_currentShip.Hardpoints[item.Position.x, item.Position.y])).ToArray(),
Crosshairs[index]
);
}).ToArray();
foreach (var crosshair in Crosshairs)
crosshair.gameObject.SetActive(false);
foreach (var group in ArticulationGroups)
group.crosshair.gameObject.SetActive(true);
LockingIndicators = _currentShip.GetBehaviors<TargetLock>().Select(x =>
{
var i = LockIndicator.Instantiate<PlaceUIElementWorldspace>();
return (x, i, i.GetComponent<Rotate>());
}).ToArray();
Cursor.lockState = CursorLockMode.Locked;
GameplayUI.SetActive(true);
_input.Player.Enable();
ShipPanel.Display(_currentShip);
ShipPanel.Display(_currentShip, true);
SchematicDisplay.ShowShip(_currentShip);
}
else
@ -593,4 +665,37 @@ public class ActionGameManager : MonoBehaviour
Zone.Update(_time, Time.deltaTime);
SectorRenderer.Time = _time;
}
private void LateUpdate()
{
UpdateTargetIndicators();
}
private void UpdateTargetIndicators()
{
if (_currentShip == null || _currentShip.Parent != null) return;
ViewDot.Target = SectorRenderer.EntityInstances[_currentShip].LookAtPoint.position;
if (_currentShip.Target.Value != null)
TargetIndicator.Target = _currentShip.Target.Value.Position;
var distance = length((float3)ViewDot.Target - _currentShip.Position);
foreach (var (_, barrels, crosshair) in ArticulationGroups)
{
var averagePosition = Vector3.zero;
foreach (var barrel in barrels)
averagePosition += barrel.position + barrel.forward * distance;
averagePosition /= barrels.Length;
crosshair.Target = averagePosition;
}
foreach (var (targetLock, indicator, spin) in LockingIndicators)
{
var showLockingIndicator = targetLock.Lock > .01f && _currentShip.Target.Value != null;
indicator.gameObject.SetActive(showLockingIndicator);
if(showLockingIndicator)
indicator.Target = _currentShip.Target.Value.Position;
indicator.NoiseAmplitude = Settings.GameplaySettings.LockIndicatorNoiseAmplitude * (1 - targetLock.Lock);
indicator.NoiseFrequency = Settings.GameplaySettings.LockIndicatorFrequency.Evaluate(targetLock.Lock);
spin.Speed = Settings.GameplaySettings.LockSpinSpeed.Evaluate(targetLock.Lock);
}
}
}

View file

@ -129,6 +129,38 @@ public class @AetheriaInput : IInputActionCollection, IDisposable
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""Target Reticle"",
""type"": ""Button"",
""id"": ""86f2e6cc-b895-4c55-aa19-70220df477d2"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""Target Previous"",
""type"": ""Button"",
""id"": ""2cf8e2b2-1463-463b-8f55-e79884f3767d"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""Target Next"",
""type"": ""Button"",
""id"": ""1e2bd5af-e174-4533-8c57-b04b7e9df92c"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
},
{
""name"": ""Target Nearest"",
""type"": ""Button"",
""id"": ""b2a42777-c22b-48f3-9e74-8dc715449845"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """"
}
],
""bindings"": [
@ -472,6 +504,50 @@ public class @AetheriaInput : IInputActionCollection, IDisposable
""action"": ""Fire Group 6"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""5211a58c-428b-4ee6-820d-2f67789806d6"",
""path"": ""<Keyboard>/r"",
""interactions"": """",
""processors"": """",
""groups"": ""Keyboard&Mouse"",
""action"": ""Target Reticle"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""6e13d87d-e5bb-4363-b153-1e0c1e21e4eb"",
""path"": ""<Keyboard>/t"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""Target Previous"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""e6e3164c-1b59-4eab-99d9-5a3bc294af0b"",
""path"": ""<Keyboard>/y"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""Target Next"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""b55dd143-367d-4842-82c8-593c301bcd69"",
""path"": ""<Keyboard>/u"",
""interactions"": """",
""processors"": """",
""groups"": ""Keyboard&Mouse"",
""action"": ""Target Nearest"",
""isComposite"": false,
""isPartOfComposite"": false
}
]
},
@ -1052,6 +1128,10 @@ public class @AetheriaInput : IInputActionCollection, IDisposable
m_Player_NextWeapon = m_Player.FindAction("Next Weapon", throwIfNotFound: true);
m_Player_PreviousWeapon = m_Player.FindAction("Previous Weapon", throwIfNotFound: true);
m_Player_ToggleWeaponGroup = m_Player.FindAction("Toggle Weapon Group", throwIfNotFound: true);
m_Player_TargetReticle = m_Player.FindAction("Target Reticle", throwIfNotFound: true);
m_Player_TargetPrevious = m_Player.FindAction("Target Previous", throwIfNotFound: true);
m_Player_TargetNext = m_Player.FindAction("Target Next", throwIfNotFound: true);
m_Player_TargetNearest = m_Player.FindAction("Target Nearest", throwIfNotFound: true);
// UI
m_UI = asset.FindActionMap("UI", throwIfNotFound: true);
m_UI_Navigate = m_UI.FindAction("Navigate", throwIfNotFound: true);
@ -1131,6 +1211,10 @@ public class @AetheriaInput : IInputActionCollection, IDisposable
private readonly InputAction m_Player_NextWeapon;
private readonly InputAction m_Player_PreviousWeapon;
private readonly InputAction m_Player_ToggleWeaponGroup;
private readonly InputAction m_Player_TargetReticle;
private readonly InputAction m_Player_TargetPrevious;
private readonly InputAction m_Player_TargetNext;
private readonly InputAction m_Player_TargetNearest;
public struct PlayerActions
{
private @AetheriaInput m_Wrapper;
@ -1149,6 +1233,10 @@ public class @AetheriaInput : IInputActionCollection, IDisposable
public InputAction @NextWeapon => m_Wrapper.m_Player_NextWeapon;
public InputAction @PreviousWeapon => m_Wrapper.m_Player_PreviousWeapon;
public InputAction @ToggleWeaponGroup => m_Wrapper.m_Player_ToggleWeaponGroup;
public InputAction @TargetReticle => m_Wrapper.m_Player_TargetReticle;
public InputAction @TargetPrevious => m_Wrapper.m_Player_TargetPrevious;
public InputAction @TargetNext => m_Wrapper.m_Player_TargetNext;
public InputAction @TargetNearest => m_Wrapper.m_Player_TargetNearest;
public InputActionMap Get() { return m_Wrapper.m_Player; }
public void Enable() { Get().Enable(); }
public void Disable() { Get().Disable(); }
@ -1200,6 +1288,18 @@ public class @AetheriaInput : IInputActionCollection, IDisposable
@ToggleWeaponGroup.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnToggleWeaponGroup;
@ToggleWeaponGroup.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnToggleWeaponGroup;
@ToggleWeaponGroup.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnToggleWeaponGroup;
@TargetReticle.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetReticle;
@TargetReticle.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetReticle;
@TargetReticle.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetReticle;
@TargetPrevious.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetPrevious;
@TargetPrevious.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetPrevious;
@TargetPrevious.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetPrevious;
@TargetNext.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetNext;
@TargetNext.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetNext;
@TargetNext.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetNext;
@TargetNearest.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetNearest;
@TargetNearest.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetNearest;
@TargetNearest.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnTargetNearest;
}
m_Wrapper.m_PlayerActionsCallbackInterface = instance;
if (instance != null)
@ -1246,6 +1346,18 @@ public class @AetheriaInput : IInputActionCollection, IDisposable
@ToggleWeaponGroup.started += instance.OnToggleWeaponGroup;
@ToggleWeaponGroup.performed += instance.OnToggleWeaponGroup;
@ToggleWeaponGroup.canceled += instance.OnToggleWeaponGroup;
@TargetReticle.started += instance.OnTargetReticle;
@TargetReticle.performed += instance.OnTargetReticle;
@TargetReticle.canceled += instance.OnTargetReticle;
@TargetPrevious.started += instance.OnTargetPrevious;
@TargetPrevious.performed += instance.OnTargetPrevious;
@TargetPrevious.canceled += instance.OnTargetPrevious;
@TargetNext.started += instance.OnTargetNext;
@TargetNext.performed += instance.OnTargetNext;
@TargetNext.canceled += instance.OnTargetNext;
@TargetNearest.started += instance.OnTargetNearest;
@TargetNearest.performed += instance.OnTargetNearest;
@TargetNearest.canceled += instance.OnTargetNearest;
}
}
}
@ -1439,6 +1551,10 @@ public class @AetheriaInput : IInputActionCollection, IDisposable
void OnNextWeapon(InputAction.CallbackContext context);
void OnPreviousWeapon(InputAction.CallbackContext context);
void OnToggleWeaponGroup(InputAction.CallbackContext context);
void OnTargetReticle(InputAction.CallbackContext context);
void OnTargetPrevious(InputAction.CallbackContext context);
void OnTargetNext(InputAction.CallbackContext context);
void OnTargetNearest(InputAction.CallbackContext context);
}
public interface IUIActions
{

View file

@ -7,6 +7,8 @@ using static Unity.Mathematics.math;
public class ArticulationPoint : MonoBehaviour
{
public Transform Target;
public int Group;
public float YawMin;
public float YawMax;

View file

@ -29,6 +29,8 @@ public class GameSettings : ScriptableObject
public Color HardpointHitColor;
public Color GearHitColor;
public Color ThermalHitColor;
public Gradient ArmorGradient;
public Gradient DurabilityGradient;
[HideInInspector] public Sprite[] ItemIcons;
}

View file

@ -6,6 +6,7 @@ using UnityEngine;
using static Unity.Mathematics.math;
using static Unity.Mathematics.noise;
using Random = UnityEngine.Random;
using static Noise1D;
public class GuidedProjectile : MonoBehaviour
{
@ -41,8 +42,9 @@ public class GuidedProjectile : MonoBehaviour
_active = _alive = true;
_phase = Random.value * 100;
_prevDist = Single.MaxValue;
var main = Particles.main;
main.startColor = Color.white;
Particles.startColor = Color.white;
//var main = Particles.main;
//main.startColor = new ParticleSystem.MinMaxGradient { mode = ParticleSystemGradientMode.Color, color = Color.white };
Particles.Clear(true);
Particles.Play(true);
}
@ -71,8 +73,7 @@ public class GuidedProjectile : MonoBehaviour
var right = cross(dir, float3(0, 1, 0));
var up = cross(dir, right);
var dodge = normalize(lerp(
normalize(right * snoise(position * Frequency + float3(1) * _phase) +
up * snoise(position * Frequency + float3(1) * (100 + _phase))),
normalize(right * noise(Time.time * Frequency + _phase) + up * noise(Time.time * Frequency + (100 + _phase))),
Vector3.up, LiftCurve.Evaluate(curveLerp)));
var desired = Vector3.Slerp(dodge, dir, GuidanceCurve.Evaluate(curveLerp)).normalized * TopSpeed;
var thrust = Thrust * ThrustCurve.Evaluate(curveLerp);
@ -80,14 +81,15 @@ public class GuidedProjectile : MonoBehaviour
}
var ray = new Ray(t.position, Velocity);
if (Physics.Raycast(ray, out var hit, Velocity.magnitude, LayerMask.NameToLayer("Combat")))
if (Physics.Raycast(ray, out var hit, Velocity.magnitude * Time.deltaTime))
{
var hull = hit.collider.GetComponent<HullCollider>();
if (hull)
{
hull.SendHit(Damage, Penetration, Spread, DamageType, SourceEntity, hit, Velocity.normalized);
}
StartCoroutine(Kill());
if (hit.transform.gameObject.layer == 1)
StartCoroutine(Kill());
}
if(_alive)
t.position += Velocity * Time.deltaTime;
@ -100,8 +102,9 @@ public class GuidedProjectile : MonoBehaviour
while (Time.time - startTime < FadeOutTime)
{
var lerp = 1 - (Time.time - startTime) / FadeOutTime;
var main = Particles.main;
main.startColor = Color.white * lerp;
Particles.startColor = Color.white * lerp;
//var main = Particles.main;
//main.startColor = new ParticleSystem.MinMaxGradient { mode = ParticleSystemGradientMode.Color, color = Color.white * lerp };
yield return null;
}

View file

@ -13,7 +13,6 @@ public class InventoryCell : MonoBehaviour
{
public Image Background;
public Image Icon;
public TextMeshProUGUI Label;
public ObservablePointerClickTrigger PointerClickTrigger;
public ObservableBeginDragTrigger BeginDragTrigger;

View file

@ -236,7 +236,7 @@ public class SectorRenderer : MonoBehaviour
}
instantWeapon.OnFire += () =>
_guidedProjectileManagers[launcherData].Launch(launcherData, item, instance, EntityInstances[entity.Target]);
_guidedProjectileManagers[launcherData].Launch(launcherData, item, instance, EntityInstances[entity.Target.Value]);
}
}
}
@ -438,6 +438,7 @@ public class SectorRenderer : MonoBehaviour
// Subtract surface damage from hardpoint armor
entity.HardpointArmor[hardpoint] = max(entity.HardpointArmor[hardpoint] - surfaceDamage, 0);
entity.HardpointDamage.OnNext((hardpoint, surfaceDamage));
var penetratingDamage = remainder + hit.Damage * hit.Penetration;
@ -639,10 +640,10 @@ public class SectorRenderer : MonoBehaviour
entity.Key.HardpointTransforms[x.Key] = (x.Value[0].position, x.Value[0].forward);
}
if (entity.Key.Target != null && !EntityInstances.ContainsKey(entity.Key.Target))
entity.Key.Target = null;
entity.Value.LookAtPoint.position = entity.Value.Transform.position + (Vector3) entity.Key.LookDirection * (entity.Key.Target != null
? (EntityInstances[entity.Key.Target].Transform.position - entity.Value.Transform.position).magnitude : 100);
if (entity.Key.Target.Value != null && !EntityInstances.ContainsKey(entity.Key.Target.Value))
entity.Key.Target.Value = null;
entity.Value.LookAtPoint.position = entity.Value.Transform.position + (Vector3) entity.Key.LookDirection * (entity.Key.Target.Value != null
? (EntityInstances[entity.Key.Target.Value].Transform.position - entity.Value.Transform.position).magnitude : 10000);
entity.Value.Transform.position = entity.Key.Position;
}

View file

@ -4,7 +4,7 @@ MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 300
executionOrder: 50
icon: {instanceID: 0}
userData:
assetBundleName:

View file

@ -15,7 +15,7 @@ using static Unity.Mathematics.noise;
public interface IBehavior
{
bool Update(float delta);
bool Execute(float delta);
BehaviorData Data { get; }
}
@ -42,7 +42,7 @@ public interface IInitializableBehavior
public interface IAlwaysUpdatedBehavior
{
void AlwaysUpdate(float delta);
void Update(float delta);
}
public interface IProgressBehavior
@ -118,6 +118,7 @@ public abstract class PersistentBehaviorData
Union(32, typeof(CockpitData)),
Union(33, typeof(HeatsinkData)),
Union(34, typeof(TurretControllerData)),
Union(35, typeof(TargetLockData)),
JsonConverter(typeof(JsonKnownTypesConverter<BehaviorData>)), JsonObject(MemberSerialization.OptIn)]
public abstract class BehaviorData
{

View file

@ -51,7 +51,7 @@ public class Capacitor : IBehavior
Item = item;
}
public bool Update(float delta)
public bool Execute(float delta)
{
Capacity = Context.Evaluate(_data.Capacity, Item.EquippableItem, Entity);
Efficiency = Context.Evaluate(_data.Efficiency, Item.EquippableItem, Entity);

View file

@ -38,7 +38,7 @@ public class Cockpit : IBehavior
Heatstroke = 0;
}
public bool Update(float delta)
public bool Execute(float delta)
{
if (Item.Temperature > Context.GameplaySettings.HeatstrokeTemperature)
{

View file

@ -39,7 +39,7 @@ public class ConstantWeapon : IBehavior, IAlwaysUpdatedBehavior
Item = item;
}
public bool Update(float delta)
public bool Execute(float delta)
{
if (!_firing)
{
@ -51,7 +51,7 @@ public class ConstantWeapon : IBehavior, IAlwaysUpdatedBehavior
return true;
}
public void AlwaysUpdate(float delta)
public void Update(float delta)
{
// Update executes after AlwaysUpdate,
// so if the stop flag didn't get disabled previous frame,

View file

@ -93,7 +93,7 @@ public abstract class ControllerBase<T> : IBehavior, IController<T>, IInitializa
Moving = false;
}
public bool Update(float delta)
public bool Execute(float delta)
{
if (Available)
{

View file

@ -42,7 +42,7 @@ public class Cooldown : IBehavior, IAlwaysUpdatedBehavior, IProgressBehavior
Context = context;
}
public bool Update(float delta)
public bool Execute(float delta)
{
if (_cooldown < 0)
{
@ -54,7 +54,7 @@ public class Cooldown : IBehavior, IAlwaysUpdatedBehavior, IProgressBehavior
}
public void AlwaysUpdate(float delta)
public void Update(float delta)
{
_cooldown -= delta / Context.Evaluate(_data.Cooldown, Item.EquippableItem, Entity);
}

View file

@ -40,7 +40,7 @@ public class EnergyDraw : IBehavior
Context = context;
}
public bool Update(float delta)
public bool Execute(float delta)
{
Entity.Energy -= Context.Evaluate(_data.Draw, Item.EquippableItem, Entity) * (_data.PerSecond ? delta : 1);
return true;

View file

@ -82,7 +82,7 @@ public class Factory : IBehavior//, IPersistentBehavior, IPopulationAssignment
Item = item;
}
public bool Update(float delta)
public bool Execute(float delta)
{
// ToolingTime = Context.Evaluate(_data.ToolingTime, Item, Entity);
// var blueprint = Context.ItemData.Get<BlueprintData>(_blueprint);

View file

@ -24,11 +24,7 @@ public class HaulingControllerData : ControllerData
public class HaulingController : ControllerBase<HaulingTask>, IBehavior, IPersistentBehavior
{
public BehaviorData Data => _data;
private HaulingControllerData _data;
private ItemManager ItemManager { get; }
private Entity Entity { get; }
private EquippedItem Item { get; }
private bool _taskStarted;
@ -39,13 +35,11 @@ public class HaulingController : ControllerBase<HaulingTask>, IBehavior, IPersis
public HaulingController(ItemManager itemManager, HaulingControllerData data, Entity entity, EquippedItem item) : base(itemManager, data, entity)
{
ItemManager = itemManager;
_data = data;
Entity = entity;
Item = item;
}
public new bool Update(float delta)
public new bool Execute(float delta)
{
if (Task != null)
{
@ -56,7 +50,7 @@ public class HaulingController : ControllerBase<HaulingTask>, IBehavior, IPersis
_taskStarted = true;
}
}
return base.Update(delta);
return base.Execute(delta);
}
// void OnOriginZoneArrival()

View file

@ -40,7 +40,7 @@ public class Heat : IBehavior
Context = context;
}
public bool Update(float delta)
public bool Execute(float delta)
{
Item.AddHeat(Context.Evaluate(_data.Heat, Item.EquippableItem, Entity) * (_data.PerSecond ? delta : 1));

View file

@ -35,7 +35,7 @@ public class Heatsink : IBehavior
Item = item;
}
public bool Update(float delta)
public bool Execute(float delta)
{
return true;
}

View file

@ -38,7 +38,7 @@ public class Hitscan : IBehavior
Item = item;
}
public bool Update(float delta)
public bool Execute(float delta)
{
// TODO: Implement hitscan weapons!
Range = Context.Evaluate(_data.Range, Item.EquippableItem, Entity);

View file

@ -37,7 +37,7 @@ public class ItemUsage : IBehavior
Context = context;
}
public bool Update(float delta)
public bool Execute(float delta)
{
var cargo = Entity.FindItemInCargo(_data.Item);
if (cargo == null) return false;

View file

@ -21,143 +21,17 @@ public class LauncherData : InstantWeaponData
[InspectableField, JsonProperty("thrust"), Key(12)]
public PerformanceStat Thrust = new PerformanceStat();
[InspectableField, JsonProperty("lockAngle"), Key(13)]
public float LockAngle;
[InspectableField, JsonProperty("frequency"), Key(14)]
[InspectableField, JsonProperty("frequency"), Key(13)]
public float DodgeFrequency;
[InspectableField, JsonProperty("launchSpeed"), Key(15)]
[InspectableField, JsonProperty("launchSpeed"), Key(14)]
public PerformanceStat LaunchSpeed = new PerformanceStat();
[InspectableField, JsonProperty("missileSpeed"), Key(16)]
[InspectableField, JsonProperty("missileSpeed"), Key(15)]
public PerformanceStat MissileSpeed = new PerformanceStat();
[InspectableField, JsonProperty("lockOnTime"), Key(17)]
public PerformanceStat LockOnTime = new PerformanceStat();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
{
return new InstantWeapon(context, this, entity, item);
}
}
public class Launcher : IBehavior, IAlwaysUpdatedBehavior
{
private bool _locking;
private float _lockingTimer;
private float _cooldown; // normalized
private bool _locked;
private LauncherData _data;
private Entity Entity { get; }
private EquippedItem Item { get; }
private ItemManager Context { get; }
private float _firingVisibility;
public BehaviorData Data => _data;
public Launcher(ItemManager context, LauncherData m, Entity entity, EquippedItem item)
{
Context = context;
_data = m;
Entity = entity;
Item = item;
// _audio = hp.Proxy.GetComponent<AudioSource>();
// if(_audio==null)
// _audio = hp.Proxy.gameObject.AddComponent<AudioSource>();
// _audio.clip = _launcher.BeepSound;
// _audio.loop = true;
// _audio.volume = .5f;
}
public bool Activate()
{
_locking = true;
_lockingTimer = 1;
return true;
}
public void Deactivate()
{
// if (_lockingTimer < 0)
// {
// Fire(0);
// if(_launcher.BurstCount>1)
// Observable.Interval(TimeSpan.FromSeconds(_launcher.BurstTime.Evaluate(Hardpoint) / (_launcher.BurstCount-1))).Take(_launcher.BurstCount-1)
// .Subscribe(l => Fire(l+1));
// _lockingTimer = _cooldown = 1;
// _locking = _locked = false;
// _audio.Stop();
// }
// _locking = false;
// _lockingTimer = 1;
}
public bool Update(float delta)
{
// _firingVisibility += _launcher.Visibility.Evaluate(Hardpoint);
// Hardpoint.Temperature += _launcher.Heat.Evaluate(Hardpoint) / Hardpoint.HeatCapacity;
// var inst = GameObject.Instantiate(_launcher.MissilePrefab).transform;
// var missile = inst.GetComponent<Bullet>();
// missile.Target = Hardpoint.Ship.Ship.Target;
// missile.Source = Hardpoint.Ship.Ship.Hitpoints;
// missile.Lifetime = _launcher.Range.Evaluate(Hardpoint) / _launcher.MissileSpeed.Evaluate(Hardpoint);
// missile.Damage = _launcher.Damage.Evaluate(Hardpoint);
// inst.position = Hardpoint.Proxy.position;
// inst.rotation = Hardpoint.Proxy.rotation;
// inst.GetComponent<Rigidbody>().velocity = _launcher.LaunchSpeed.Evaluate(Hardpoint) * Hardpoint.Proxy.forward;
// Physics.IgnoreCollision(Hardpoint.Ship.Ship.GetComponent<Collider>(), inst.GetComponent<Collider>());
// var proj = inst.gameObject.AddComponent<GuidedProjectile>();
// proj.GuidanceCurve = _launcher.GuidanceCurve;
// proj.ThrustCurve = _launcher.ThrustCurve;
// proj.LiftCurve = _launcher.LiftCurve;
// proj.TopSpeed = _launcher.MissileSpeed.Evaluate(Hardpoint);
// proj.Frequency = _launcher.DodgeFrequency;
// proj.Target = Hardpoint.Ship.Ship.Target;
// proj.Source = Hardpoint.Ship.Ship.Hitpoints;
// proj.Thrust = _launcher.Thrust.Evaluate(Hardpoint);
// _audio.PlayOneShot(_launcher.Sounds.RandomElement());
// Debug.Log($"Firing bullet {b}");
return true;
}
public void AlwaysUpdate(float delta)
{
// if (Ship.Target == null)
// return;
//
// if (_locking && _cooldown < 0)
// {
// //if the crosshair stays under a certain LockOnBuffer distance for a certain amount of time (LockOnTime)
// if (acos(Vector2.Dot(Ship.Direction, (Ship.Target.transform.position-Ship.transform.position).normalized)) * Mathf.Rad2Deg < _launcher.LockOnDegrees)
// {
// var d = delta / _launcher.LockOnTime.Evaluate(Hardpoint);
// _lockingTimer -= d;
// if (!_locked && _lockingTimer < 0)
// {
// _locked = true;
// _audio.Play();
// } else if(Mathf.Repeat(_lockingTimer,1.0f/(_launcher.Beeps+1))-d<0)
// GameManager.Instance.InterfaceAudio.PlayOneShot(_launcher.BeepSound);
// }
// else
// {
// _lockingTimer = 1;
// _audio.Stop();
// }
// }
// else
// {
// _cooldown -= delta / _launcher.Cooldown.Evaluate(Hardpoint);
// }
//
//
// if (_firingVisibility > 0.01f)
// {
// Hardpoint.Ship.Visibility += _firingVisibility;
// _firingVisibility = 0;
// }
}
}

View file

@ -22,7 +22,6 @@ public class MiningControllerData : ControllerData
public class MiningController : ControllerBase<Mining>, IBehavior, IPersistentBehavior, IInitializableBehavior
{
public BehaviorData Data => _data;
private MiningControllerData _data;
private EquippedItem Item { get; }
@ -44,7 +43,7 @@ public class MiningController : ControllerBase<Mining>, IBehavior, IPersistentBe
base.Initialize();
}
public new bool Update(float delta)
public new bool Execute(float delta)
{
// if (Task != null)
// {
@ -88,7 +87,7 @@ public class MiningController : ControllerBase<Mining>, IBehavior, IPersistentBe
// }
// }
// }
return base.Update(delta);
return base.Execute(delta);
}
// private void OnArriveHome()

View file

@ -52,7 +52,7 @@ public class MiningTool : IBehavior
Context = context;
}
public bool Update(float delta)
public bool Execute(float delta)
{
Range = Context.Evaluate(_data.Range, Item.EquippableItem, Entity);
var asteroidTransform = Entity.Zone.GetAsteroidTransform(AsteroidBelt, Asteroid);

View file

@ -45,7 +45,7 @@ public class PatrolController : IBehavior, IInitializableBehavior
RandomTarget();
}
public bool Update(float delta)
public bool Execute(float delta)
{
_locomotion.Objective = Entity.Zone.GetOrbitPosition(_targetOrbit);
_locomotion.Update(delta);

View file

@ -37,7 +37,7 @@ public class Radiance : IBehavior
Context = context;
}
public bool Update(float delta)
public bool Execute(float delta)
{
// TODO: Light system!
return true;

View file

@ -39,7 +39,7 @@ public class Radiator : IBehavior
Item = item;
}
public bool Update(float delta)
public bool Execute(float delta)
{
Emissivity = Context.Evaluate(_data.Emissivity, Item.EquippableItem, Entity);
var rad = pow(Item.Temperature, Context.GameplaySettings.HeatRadiationExponent) * Context.GameplaySettings.HeatRadiationMultiplier * Emissivity;

View file

@ -62,7 +62,7 @@ public class Reactor : IBehavior, IOrderedBehavior
});
}
public bool Update(float delta)
public bool Execute(float delta)
{
var charge = Context.Evaluate(_data.Charge, Item.EquippableItem, Entity) * delta;
var efficiency = Context.Evaluate(_data.Efficiency, Item.EquippableItem, Entity);

View file

@ -40,7 +40,7 @@ public class Reflector : IBehavior
Item = item;
}
public bool Update(float delta)
public bool Execute(float delta)
{
// TODO: Light system!
return true;

View file

@ -65,7 +65,7 @@ public class ResourceScanner : IBehavior, IAlwaysUpdatedBehavior
Context = context;
}
public bool Update(float delta)
public bool Execute(float delta)
{
var planetData = Context.ItemData.Get<BodyData>(ScanTarget);
if (planetData != null)
@ -103,7 +103,7 @@ public class ResourceScanner : IBehavior, IAlwaysUpdatedBehavior
return false;
}
public void AlwaysUpdate(float delta)
public void Update(float delta)
{
Range = Context.Evaluate(_data.Range, Item.EquippableItem, Entity);
MinimumDensity = Context.Evaluate(_data.MinimumDensity, Item.EquippableItem, Entity);

View file

@ -35,7 +35,7 @@ public class Sensor : IBehavior
Context = context;
}
public bool Update(float delta)
public bool Execute(float delta)
{
// TODO: Handle Active Detection / Visibility From Reflected Radiance
return true;

View file

@ -42,7 +42,7 @@ public class Shield : IBehavior
// TODO: Detect hits on Ship, keep a list of callbacks that modify the hit by reference
}
public bool Update(float delta)
public bool Execute(float delta)
{
return true;
}

View file

@ -81,7 +81,7 @@ public class StatModifier : IBehavior, IInitializableBehavior, IDisposableBehavi
}
}
public bool Update(float delta)
public bool Execute(float delta)
{
foreach (var stat in _stats)
(_data.Type == StatModifierType.Constant

View file

@ -24,7 +24,6 @@ public class SurveyControllerData : ControllerData
public class SurveyController : ControllerBase<Survey>, IBehavior, IPersistentBehavior, IInitializableBehavior
{
private EquippedItem Item { get; }
public BehaviorData Data => _data;
private SurveyControllerData _data;
private bool _taskStarted;
@ -46,7 +45,7 @@ public class SurveyController : ControllerBase<Survey>, IBehavior, IPersistentBe
base.Initialize();
}
public new bool Update(float delta)
public new bool Execute(float delta)
{
// var corporation = _context.ItemData.Get<Corporation>(_entity.Corporation);
// if (surveyTask != null)
@ -103,7 +102,7 @@ public class SurveyController : ControllerBase<Survey>, IBehavior, IPersistentBe
// }
// }
// }
return base.Update(delta);
return base.Execute(delta);
}
private void NextPlanet()

View file

@ -36,7 +36,7 @@ public class Switch : IBehavior
Context = context;
}
public bool Update(float delta)
public bool Execute(float delta)
{
return Activated;
}

View file

@ -0,0 +1,87 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[MessagePackObject, JsonObject(MemberSerialization.OptIn), Order(-11), RuntimeInspectable]
public class TargetLockData : BehaviorData
{
[InspectableField, JsonProperty("speed"), Key(1), RuntimeInspectable]
public PerformanceStat Speed = new PerformanceStat();
[InspectableField, JsonProperty("sensorImpact"), Key(2), RuntimeInspectable]
public PerformanceStat SensorImpact = new PerformanceStat();
[InspectableField, JsonProperty("threshold"), Key(3), RuntimeInspectable]
public PerformanceStat Threshold = new PerformanceStat();
[InspectableField, JsonProperty("directionImpact"), Key(4), RuntimeInspectable]
public PerformanceStat DirectionImpact = new PerformanceStat();
[InspectableField, JsonProperty("decay"), Key(5), RuntimeInspectable]
public PerformanceStat Decay = new PerformanceStat();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
{
return new TargetLock(context, this, entity, item);
}
}
public class TargetLock : IBehavior, IAlwaysUpdatedBehavior
{
private TargetLockData _data;
public Entity Entity { get; }
public EquippedItem Item { get; }
public ItemManager Context { get; }
public BehaviorData Data => _data;
public float Lock { get; private set; }
public float Speed { get; private set; }
public float SensorImpact { get; private set; }
public float Threshold { get; private set; }
public float DirectionImpact { get; private set; }
public float Decay { get; private set; }
public TargetLock(ItemManager context, TargetLockData data, Entity entity, EquippedItem item)
{
Context = context;
_data = data;
Entity = entity;
Item = item;
}
public bool Execute(float delta)
{
// TODO: Hook into sensory systems to influence lock speed
return Lock > .99f;
}
public void Update(float delta)
{
if (Entity.Target.Value != null)
{
Speed = Context.Evaluate(_data.Speed, Item.EquippableItem, Entity);
SensorImpact = Context.Evaluate(_data.SensorImpact, Item.EquippableItem, Entity);
Threshold = Context.Evaluate(_data.Threshold, Item.EquippableItem, Entity);
DirectionImpact = Context.Evaluate(_data.DirectionImpact, Item.EquippableItem, Entity);
Decay = Context.Evaluate(_data.Decay, Item.EquippableItem, Entity);
var degrees = acos(dot(normalize(Entity.Target.Value.Position - Entity.Position), normalize(Entity.LookDirection))) * 57.2958f;
if (degrees < Threshold)
{
var lerp = 1 - unlerp(0, 90, degrees);
Lock = saturate(Lock + pow(lerp, DirectionImpact) * delta * Speed);
return;
}
}
Lock = saturate(Lock - Decay * delta);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7d1880b94a9e9f74e9c13be8d5fd8dee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -42,7 +42,7 @@ public class Thermotoggle : IBehavior
TargetTemperature = data.TargetTemperature;
}
public bool Update(float delta)
public bool Execute(float delta)
{
return Item.Temperature < TargetTemperature ^ _data.HighPass;
}

View file

@ -63,7 +63,7 @@ public class Thruster : IAnalogBehavior
Torque = -dot(toCenter, float2(1, 0).Rotate(item.EquippableItem.Rotation));
}
public bool Update(float delta)
public bool Execute(float delta)
{
Thrust = Context.Evaluate(_data.Thrust, Item.EquippableItem, Entity);
Entity.Velocity -= Entity.Direction.Rotate(Item.EquippableItem.Rotation) * _input * Thrust / Entity.Mass * delta;

View file

@ -22,7 +22,6 @@ public class TowingControllerData : ControllerData
public class TowingController : ControllerBase<StationTowing>, IBehavior, IPersistentBehavior
{
public BehaviorData Data => _data;
private TowingControllerData _data;
private EquippedItem Item { get; }
@ -34,7 +33,7 @@ public class TowingController : ControllerBase<StationTowing>, IBehavior, IPersi
Item = item;
}
public new bool Update(float delta)
public new bool Execute(float delta)
{
if (Task != null)
{
@ -44,7 +43,7 @@ public class TowingController : ControllerBase<StationTowing>, IBehavior, IPersi
_taskStarted = true;
}
}
return base.Update(delta);
return base.Execute(delta);
}
// void OnZoneArrival()

View file

@ -45,7 +45,7 @@ public class Trigger : IBehavior
{
}
public bool Update(float delta)
public bool Execute(float delta)
{
if (_pulled)
{

View file

@ -57,7 +57,7 @@ public class Turning : IAnalogBehavior
{
}
public bool Update(float delta)
public bool Execute(float delta)
{
Torque = Context.Evaluate(_data.Torque, Item.EquippableItem, Entity);
Entity.Direction = mul(Entity.Direction, Unity.Mathematics.float2x2.Rotate(_input * Torque / Entity.Mass * delta));

View file

@ -66,11 +66,11 @@ public class TurretController : IBehavior
}
}
public bool Update(float delta)
public bool Execute(float delta)
{
if (EquippedEntity.Target != null)
if (EquippedEntity.Target.Value != null)
{
var diff = EquippedEntity.Target.Position - EquippedEntity.Position;
var diff = EquippedEntity.Target.Value.Position - EquippedEntity.Position;
EquippedEntity.LookDirection = normalize(diff);
var dist = length(diff);
@ -86,7 +86,7 @@ public class TurretController : IBehavior
}
else
{
EquippedEntity.Target = EquippedEntity.Zone.Entities.FirstOrDefault(e => e is Ship);
EquippedEntity.Target.Value = EquippedEntity.Zone.Entities.FirstOrDefault(e => e is Ship);
}
return true;
}

View file

@ -41,7 +41,7 @@ public class VelocityConversion : IBehavior
{
}
public bool Update(float delta)
public bool Execute(float delta)
{
return true;
}

View file

@ -44,7 +44,7 @@ public class VelocityLimit : IBehavior
{
}
public bool Update(float delta)
public bool Execute(float delta)
{
Limit = Context.Evaluate(_data.TopSpeed, Item.EquippableItem, Entity);
if (length(Entity.Velocity) > Limit)

View file

@ -42,13 +42,13 @@ public class Visibility : IBehavior, IAlwaysUpdatedBehavior
Context = context;
}
public bool Update(float delta)
public bool Execute(float delta)
{
Entity.VisibilitySources[this] = Context.Evaluate(_data.Visibility, Item.EquippableItem, Entity);
return true;
}
public void AlwaysUpdate(float delta)
public void Update(float delta)
{
// TODO: Time independent decay?
if(Entity.VisibilitySources.ContainsKey(this))

View file

@ -27,7 +27,6 @@ public class WanderControllerData : ControllerData
public class WanderController : ControllerBase<WanderTask>, IBehavior
{
public WanderTarget WanderTarget;
public BehaviorData Data => _data;
private WanderControllerData _data;
private EquippedItem Item { get; }
@ -40,7 +39,7 @@ public class WanderController : ControllerBase<WanderTask>, IBehavior
Item = item;
}
public new bool Update(float delta)
public new bool Execute(float delta)
{
if (!Moving && _dockTime < 0)
{
@ -48,7 +47,7 @@ public class WanderController : ControllerBase<WanderTask>, IBehavior
}
_dockTime -= delta;
return base.Update(delta);
return base.Execute(delta);
}
private void NextTarget()

View file

@ -65,53 +65,29 @@ public class InstantWeapon : IBehavior, IAlwaysUpdatedBehavior
Item = item;
}
// private void Fire()
// {
// Hardpoint.Temperature += _projectileWeapon.Heat.Evaluate(Hardpoint) / Hardpoint.HeatCapacity;
// var inst = GameObject.Instantiate(_projectileWeapon.BulletPrefab).transform;
// Physics.IgnoreCollision(Hardpoint.Ship.Ship.GetComponent<Collider>(), inst.GetComponent<Collider>());
// var bullet = inst.GetComponent<Bullet>();
// bullet.Target = Hardpoint.Ship.Ship.Target;
// bullet.Source = Hardpoint.Ship.Ship.Hitpoints;
// bullet.Lifetime = _projectileWeapon.Range.Evaluate(Hardpoint) / _projectileWeapon.Velocity.Evaluate(Hardpoint);
// bullet.Damage = _projectileWeapon.Damage.Evaluate(Hardpoint);
// inst.position = Hardpoint.Proxy.position;
// inst.rotation = Hardpoint.Proxy.rotation;
// inst.GetComponent<Rigidbody>().velocity = _projectileWeapon.Velocity.Evaluate(Hardpoint) * Vector3.RotateTowards(-inst.forward, Hardpoint.Ship.Ship.Direction, _projectileWeapon.Deflection * Mathf.Deg2Rad, 1);
// Hardpoint.Ship.Ship.AudioSource.PlayOneShot(_projectileWeapon.Sounds.RandomElement());
// Debug.Log($"Firing bullet {b}");
// }
public bool Update(float delta)
public bool Execute(float delta)
{
_burstCount = _data.BurstCount;
_burstTime = Context.Evaluate(_data.BurstTime, Item.EquippableItem, Entity) / _burstCount;
if (_burstTime < .01f)
{
for(int i=0; i<_data.BurstCount; i++)
OnFire?.Invoke();
}
else
{
_burstCount = _data.BurstCount;
Fire();
}
_burstTimer = 0;
Fire(delta);
return true;
}
private void Fire()
private void Fire(float delta)
{
_burstCount--;
_burstTimer = _burstTime;
OnFire?.Invoke();
}
public void AlwaysUpdate(float delta)
{
if(_burstCount > 0)
_burstTimer -= delta;
while (_burstTimer < 0 && _burstCount > 0)
{
_burstTimer -= delta;
if(_burstTimer < 0)
Fire();
_burstCount--;
_burstTimer += _burstTime;
OnFire?.Invoke();
}
}
public void Update(float delta)
{
if(_burstCount > 0)
Fire(delta);
}
}

View file

@ -38,7 +38,7 @@ public abstract class Entity
public Entity Parent;
public List<Entity> Children = new List<Entity>();
public Entity Target;
public ReactiveProperty<Entity> Target = new ReactiveProperty<Entity>((Entity)null);
public float3 LookDirection;
@ -74,6 +74,11 @@ public abstract class Entity
public Subject<(int2 pos, float damage)> ArmorDamage = new Subject<(int2, float)>();
public Subject<(EquippedItem item, float damage)> ItemDamage = new Subject<(EquippedItem, float)>();
public Subject<float> HullDamage = new Subject<float>();
public UniRx.IObservable<EquippedItem> ItemDestroyed;
public UniRx.IObservable<int2> HullArmorDepleted;
public UniRx.IObservable<HardpointData> HardpointArmorDepleted;
public bool Active
{
@ -106,6 +111,10 @@ public abstract class Entity
TriggerGroups = new List<EquippedItem>[itemManager.GameplaySettings.TriggerGroupCount];
for(int i=0; i<itemManager.GameplaySettings.TriggerGroupCount; i++)
TriggerGroups[i] = new List<EquippedItem>();
ItemDestroyed = ItemDamage.Where(x => x.item.EquippableItem.Durability < .01f).Select(x=>x.item);
HullArmorDepleted = ArmorDamage.Where(x => Armor[x.pos.x, x.pos.y] < .01f).Select(x => x.pos);
HardpointArmorDepleted = HardpointDamage.Where(x => HardpointArmor[x.hardpoint] < .01f).Select(x => x.hardpoint);
}
private void MapEntity()
@ -523,7 +532,7 @@ public abstract class Entity
heatTransfer += (Temperature[v.x, v.y - 1] - temp) * Conductivity[v.x, v.y].z * Conductivity[v.x, v.y - 1].x;
if (v.y < hullData.Shape.Height - 1)
heatTransfer += (Temperature[v.x, v.y + 1] - temp) * Conductivity[v.x, v.y].x * Conductivity[v.x, v.y + 1].z;;
heatTransfer += (Temperature[v.x, v.y + 1] - temp) * Conductivity[v.x, v.y].x * Conductivity[v.x, v.y + 1].z;
newTemp[v.x, v.y] = Temperature[v.x, v.y] + heatTransfer * min(ItemManager.GameplaySettings.HeatConductionMultiplier * delta,1) / ThermalMass[v.x,v.y];
@ -617,6 +626,8 @@ public class EquippedItem
public int SortPosition;
public bool Online => EquippableItem.Durability > .01f && Temperature > _data.MinimumTemperature && Temperature < _data.MaximumTemperature;
public float Temperature
{
get
@ -673,23 +684,27 @@ public class EquippedItem
public void Update(float delta)
{
// if(Temperature < _data.MinimumTemperature || Temperature > _data.MaximumTemperature)
// {
// EquippableItem.Durability -= delta;
// return;
// }
foreach (var behavior in Behaviors.Where(b => b is IAlwaysUpdatedBehavior).Cast<IAlwaysUpdatedBehavior>())
behavior.AlwaysUpdate(delta);
foreach (var group in BehaviorGroups)
if (Temperature < _data.MinimumTemperature || Temperature > _data.MaximumTemperature)
{
foreach (var behavior in group.Behaviors)
EquippableItem.Durability -= delta;
}
foreach (var behavior in Behaviors.Where(b => b is IAlwaysUpdatedBehavior).Cast<IAlwaysUpdatedBehavior>())
behavior.Update(delta);
if (Online)
{
foreach (var group in BehaviorGroups)
{
if (!behavior.Update(delta))
break;
foreach (var behavior in group.Behaviors)
{
if (!behavior.Execute(delta))
break;
}
}
}
}
}

View file

@ -0,0 +1,34 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public static class Noise1D
{
private const float HASHSCALE = 0.1031f;
static float hash(float p)
{
float3 p3 = frac(float3(p) * HASHSCALE);
p3 += dot(p3, p3.yzx + 19.19f);
return frac((p3.x + p3.y) * p3.z);
}
static float fade(float t) { return t * t * t * (t * (6f* t - 15f) + 10f); }
static float grad(float hash, float p)
{
int i = (int)(1e4 * hash);
return (i & 1) == 0 ? p : -p;
}
public static float noise(float p)
{
float pi = floor(p), pf = p - pi, w = fade(pf);
return lerp(grad(hash(pi), pf), grad(hash(pi + 1.0f), pf - 1.0f), w) * 2.0f;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 622b46440effa29418055a226c3db195
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -104,4 +104,7 @@ public class GameplaySettings
public float HeatstrokeExponent = 2;
public float HeatstrokeRecoverySpeed = .2f;
public float HeatstrokeControlLimit = .75f;
public float LockIndicatorNoiseAmplitude = 50f;
public ExponentialLerp LockIndicatorFrequency;
public ExponentialLerp LockSpinSpeed;
}

View file

@ -62,7 +62,7 @@ public class Ship : Entity
foreach (var thruster in _reverseThrusters) thruster.Axis += -MovementDirection.y;
var deltaRot = dot(normalize(LookDirection.xz), normalize(Direction).Rotate(ItemRotation.Clockwise));
if (abs(deltaRot) < .01) deltaRot = 0;
if (abs(deltaRot) < .0001) deltaRot = 0;
deltaRot = pow(abs(deltaRot), .5f) * sign(deltaRot);
foreach (var thruster in _clockwiseThrusters) thruster.Axis += deltaRot;

View file

@ -34,8 +34,8 @@ public class InventoryPanel : MonoBehaviour
public ExponentialLerp TemperatureAlphaCurve;
public float MaxTemperature;
public bool FitToContent;
public float CellHealthPersistDuration;
public float CellHealthFadeTime;
public float CellHitPulseTime;
public Color CellBackgroundColor = new Color(0, 0, 0, .75f);
Subject<InventoryEventData> _onBeginDrag;
Subject<InventoryEventData> _onDrag;
@ -57,8 +57,10 @@ public class InventoryPanel : MonoBehaviour
public Dictionary<int2, InventoryCell> CellInstances = new Dictionary<int2, InventoryCell>();
private List<IDisposable> _subscriptions = new List<IDisposable>();
private Dictionary<int2, float> _cellHealthFadeoutTime = new Dictionary<int2, float>();
private Dictionary<int2, Dictionary<HitType, string>> _cellQueuedLabels = new Dictionary<int2, Dictionary<HitType, string>>();
private Dictionary<int2, int> _cellAnimationSequence = new Dictionary<int2, int>();
private int _hitSequence = 0;
private bool _hud;
private int2[] _offsets = {
int2(0, 1),
@ -123,33 +125,6 @@ public class InventoryPanel : MonoBehaviour
}
_temperatureTexture.Apply();
TemperatureDisplay.rectTransform.anchoredPosition = _firstRect.anchoredPosition - Vector2.one * Grid.cellSize * 1.5f;
foreach (var damagedCell in _cellHealthFadeoutTime.Keys.ToArray())
{
var fadeoutTime = _cellHealthFadeoutTime[damagedCell];
if (fadeoutTime < Time.time)
{
StartCoroutine(FadeOutLabel(CellInstances[damagedCell]));
_cellHealthFadeoutTime.Remove(damagedCell);
_cellQueuedLabels[damagedCell].Clear();
continue;
}
var queuedLabels = _cellQueuedLabels[damagedCell];
var currentLabel = queuedLabels.ElementAt((int) ((fadeoutTime - Time.time) / CellHealthPersistDuration * queuedLabels.Count));
if (CellInstances[damagedCell].Label.text != currentLabel.Value)
{
CellInstances[damagedCell].Label.text = currentLabel.Value;
CellInstances[damagedCell].Label.color = currentLabel.Key switch
{
HitType.Armor => Settings.ArmorHitColor,
HitType.Hardpoint => Settings.HardpointHitColor,
HitType.Gear => Settings.GearHitColor,
HitType.Thermal => Settings.ThermalHitColor,
_ => Color.white
};
}
}
}
}
@ -167,8 +142,6 @@ public class InventoryPanel : MonoBehaviour
Destroy(empty);
EmptyCells.Clear();
_cellQueuedLabels.Clear();
foreach(var node in CellInstances.Values)
node.GetComponent<Prototype>().ReturnToPool();
CellInstances.Clear();
@ -182,9 +155,10 @@ public class InventoryPanel : MonoBehaviour
Title.text = "None";
}
public void Display(Entity entity)
public void Display(Entity entity, bool hud = false)
{
Clear();
_hud = hud;
_displayedEntity = entity;
_firstRect = null;
@ -224,7 +198,6 @@ public class InventoryPanel : MonoBehaviour
}
else
{
_cellQueuedLabels.Add(v, new Dictionary<HitType, string>(4));
var cell = NodePrototype.Instantiate<InventoryCell>();
if (!_firstRect)
_firstRect = cell.GetComponent<RectTransform>();
@ -247,58 +220,55 @@ public class InventoryPanel : MonoBehaviour
_subscriptions.Add(entity.ArmorDamage.Subscribe(hit =>
{
var labelText = $"{((int) (entity.Armor[hit.pos.x, hit.pos.y] / hullData.Armor * 100)).ToString()}%";
// If there is no set fadeout time, that means this is the first hit and the cell label isn't visible yet
if (!_cellHealthFadeoutTime.ContainsKey(hit.pos)) StartCoroutine(FadeInLabel(CellInstances[hit.pos]));
// Color and label text will be set according to remaining time until fadeout
_cellQueuedLabels[hit.pos][HitType.Armor] = labelText;
// Set the fadeout time to some time in the future
_cellHealthFadeoutTime[hit.pos] = Time.time + CellHealthPersistDuration;
//RefreshCells(new []{int2(hit.pos)});
var hitCells = new[] { hit.pos };
StartCoroutine(Pulse(hitCells, HitType.Armor, _hitSequence++));
RefreshCells(hitCells);
}));
_subscriptions.Add(entity.ItemDamage.Subscribe(hit =>
{
var data = entity.ItemManager.GetData(hit.item.EquippableItem);
var labelText = $"{((int) (hit.item.EquippableItem.Durability / data.Durability * 100)).ToString()}%";
if (!_cellHealthFadeoutTime.ContainsKey(hit.item.Position)) StartCoroutine(FadeInLabel(CellInstances[hit.item.Position]));
_cellQueuedLabels[hit.item.Position][data.HardpointType == HardpointType.Thermal ? HitType.Thermal : HitType.Gear] = labelText;
_cellHealthFadeoutTime[hit.item.Position] = Time.time + CellHealthPersistDuration;
var hitCells = data.Shape.Coordinates.Select(v => v + hit.item.Position).ToArray();
StartCoroutine(Pulse(hitCells, HitType.Armor, _hitSequence++));
RefreshCells(hitCells);
}));
_subscriptions.Add(entity.HardpointDamage.Subscribe(hit =>
{
var labelText = $"{((int) (entity.HardpointArmor[hit.hardpoint] / hit.hardpoint.Armor * 100)).ToString()}%";
if (!_cellHealthFadeoutTime.ContainsKey(hit.hardpoint.Position)) StartCoroutine(FadeInLabel(CellInstances[hit.hardpoint.Position]));
_cellQueuedLabels[hit.hardpoint.Position][HitType.Hardpoint] = labelText;
_cellHealthFadeoutTime[hit.hardpoint.Position] = Time.time + CellHealthPersistDuration;
var hitCells = hit.hardpoint.Shape.Coordinates.Select(v => v + hit.hardpoint.Position).ToArray();
StartCoroutine(Pulse(hitCells, HitType.Armor, _hitSequence++));
RefreshCells(hitCells);
}));
}
private IEnumerator FadeInLabel(InventoryCell cell)
private IEnumerator Pulse(int2[] cells, HitType hitType, int sequence)
{
cell.Label.gameObject.SetActive(true);
float startTime = Time.time;
while (Time.time - startTime < CellHealthFadeTime)
foreach (var cell in cells)
{
var lerp = (Time.time - startTime) / CellHealthFadeTime;
cell.Label.alpha = lerp;
if(_cellAnimationSequence.ContainsKey(cell))
_cellAnimationSequence[cell] = max(_cellAnimationSequence[cell], sequence);
else
_cellAnimationSequence[cell] = sequence;
}
var hitColor = hitType switch
{
HitType.Armor => Settings.ArmorHitColor,
HitType.Hardpoint => Settings.HardpointHitColor,
HitType.Gear => Settings.GearHitColor,
HitType.Thermal => Settings.ThermalHitColor,
_ => Color.white
};
float startTime = Time.time;
while (Time.time - startTime < CellHitPulseTime)
{
var lerp = (Time.time - startTime) / CellHitPulseTime;
foreach(var cell in cells)
if(_cellAnimationSequence[cell] == sequence)
CellInstances[cell].Background.color = Color.Lerp(hitColor, CellBackgroundColor, lerp);
yield return null;
}
cell.Label.alpha = 1;
}
private IEnumerator FadeOutLabel(InventoryCell cell)
{
float startTime = Time.time;
while (Time.time - startTime < CellHealthFadeTime)
{
var lerp = (Time.time - startTime) / CellHealthFadeTime;
cell.Label.alpha = 1 - lerp;
yield return null;
}
cell.Label.alpha = 0;
cell.Label.gameObject.SetActive(false);
foreach (var cell in cells)
CellInstances[cell].Background.color = CellBackgroundColor;
}
public void Display(EquippedCargoBay cargo)
@ -446,8 +416,19 @@ public class InventoryPanel : MonoBehaviour
{
var hullData = GameManager.ItemManager.GetData(_displayedEntity.Hull) as HullData;
var interior = hullData.InteriorCells[position];
var item = FakeOccupancy?[position]??false ? FakeEquipment : IgnoreOccupancy?[position]??false ? null : _displayedEntity.GearOccupancy[position.x, position.y];
var hardpoint = _displayedEntity.Hardpoints[position.x, position.y];
var item = FakeOccupancy?[position] ?? false ? FakeEquipment : IgnoreOccupancy?[position] ?? false ? null : _displayedEntity.GearOccupancy[position.x, position.y];
if (_hud)
{
if (!interior && _displayedEntity.Armor[position.x, position.y] > .01f)
return Settings.ArmorGradient.Evaluate(_displayedEntity.Armor[position.x, position.y] / hullData.Armor);
else if (hardpoint != null && _displayedEntity.HardpointArmor[hardpoint] > .01f)
return Settings.ArmorGradient.Evaluate(_displayedEntity.HardpointArmor[hardpoint] / hardpoint.Armor);
if (item != null) return Settings.DurabilityGradient.Evaluate(item.EquippableItem.Durability / _displayedEntity.ItemManager.GetData(item.EquippableItem).Durability);
return Color.white * .25f;
}
if (hardpoint == null)
{

View file

@ -0,0 +1,52 @@
using UnityEngine;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using static Unity.Mathematics.noise;
using static Noise1D;
/// <summary>
/// Place an UI element to a world position
/// </summary>
[RequireComponent(typeof(RectTransform))]
public class PlaceUIElementWorldspace : MonoBehaviour
{
public float NoiseAmplitude;
public float NoiseFrequency;
public RectTransform CanvasRectTransform;
public float BorderPixels = 10;
public Vector3 Target;
private RectTransform _rectTransform;
private Transform _cameraTransform;
private float _noiseOffset;
void Start()
{
// Get the rect transform
_rectTransform = GetComponent<RectTransform>();
_cameraTransform = Camera.main.transform;
}
private void OnEnable()
{
_noiseOffset = UnityEngine.Random.Range(-100f, 100f);
}
/// <summary>
/// Move the UI element to the world position
/// </summary>
void LateUpdate()
{
if (Target == null)
return;
_noiseOffset += Time.deltaTime * NoiseFrequency;
Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(Camera.main, Target);
screenPoint *= Mathf.Sign(Vector3.Dot(_cameraTransform.forward, Target - _cameraTransform.position));
screenPoint += new Vector2(noise(_noiseOffset), noise(10 + _noiseOffset)) * NoiseAmplitude;
screenPoint = new Vector2(Mathf.Clamp(screenPoint.x, BorderPixels, Screen.width - BorderPixels),Mathf.Clamp(screenPoint.y, BorderPixels, Screen.height - BorderPixels));
_rectTransform.anchoredPosition = screenPoint - CanvasRectTransform.sizeDelta / 2f;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 79e1b49bde6c1c54aa6b5c2256e0e382
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: